#!/bin/sh /etc/rc.common
# /etc/init.d/spoofer

# We want to run spoofer-prober weekly using cron, starting nowish if it has
# not run in the last week.  We avoid a fixed day and time so that if this is
# installed on many hosts, they don't all flood the spoofer server at once.
# Specific cases that warrant starting nowish include:
# - spoofer has just been installed
# - the machine was just booted and prober has not run in the last week
# - manual "/etc/init.d/spoofer start" and prober has not run in the last week

START=99
STOP=01

MINDATE=1514764800; # 2018-01-01

. /usr/share/spoofer/spoofer-lib.sh

start() {
    NOW=$(date +'%s')
    # Create spoofer config in UCI if needed
    spoofer_init_config
    if uptime | egrep 'up 0 min' >/dev/null || test "$NOW" -lt "$MINDATE"; then
	# Machine just booted or clock is very wrong.  (On hardware without an
	# RTC, clock is inaccurate until ntp does its thing.)
	if crontab_l | egrep "$STARTTAG" >/dev/null; then
	    log "The spoofer startup cronjob already exists."
	else
	    log "Adding spoofer startup cronjob to wait for clock correction."
	    add_spoofer_job "*/5 * * * * /etc/init.d/spoofer start; $STARTTAG"
	fi
    else
	# Clock seems reasonable.  Add a prober cronjob for now-ish, or 1 week
	# after the last run, whichever is later.
	START=$(expr "$NOW" + 120)
	LAST=$(uci_get spoofer @result[0] start 0)
	NEXT=$(expr $LAST + 604800)
	if test "$NEXT" -gt "$START"; then
	    START="$NEXT"
	fi
	log $(date -d"@$START" +'Adding spoofer prober cronjob on weekday %w, %H:%M')
	add_spoofer_job "$(date -d"@$START" +'%M %H * * %w') spoofer; $PROBERTAG"
    fi
}

stop() {
    log "Removing spoofer cronjobs."
    crontab_l | egrep -v "$STARTTAG|$PROBERTAG" | crontab -
}

add_spoofer_job() {
    { crontab_l | egrep -v "$STARTTAG|$PROBERTAG"; echo "$@"; } | crontab -
    /etc/init.d/cron start
    /etc/init.d/cron enable
}

log() {
    logger -t spoofer "$@"
}
