#!/bin/bash
#
# VERSION=11
# CHANGES="Update crontab the right way."

export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/local/bin:/usr/local/sbin:/usr/fallback

BEROCONF=/usr/fallback/beroconf

function log () {
	echo "[init_cron] ${1}"
}

function setup_cron () {
	if [ ! -d /usr/conf/cron ] ; then
		mkdir -p /usr/conf/cron
	fi

	if [ -f /usr/conf/cron/root ]; then
		mv /usr/conf/cron/root /usr/conf/cron/old.root
	fi
	touch /usr/conf/cron/root

	crontab -l | grep -v "cron_working" > /tmp/crontab.cron
	if [ "${1}" = "on" ]; then
		log "Adding cron-job."
		echo "*/5 * * * * /bin/touch /var/run/cron_working" >> /tmp/crontab.cron
	else
		log "Removing cron-job."
	fi
	crontab /tmp/crontab.cron
	rm -f /tmp/crontab.cron
}

function start_cron () {
	log "Starting crond."
	/sbin/start-stop-daemon -S -m -p /var/run/crond -x /usr/sbin/crond -- -c /usr/conf/cron -l0
}

function setup_cron_recovery () {
	[ ! -d /usr/conf/cron ] && mkdir -p /usr/conf/cron
	crontab -l | grep -v 'recovery-mode' > /tmp/crontab.cron
	if [ "${1}" = "on" ]; then
		echo "*/5 * * * * /bin/bash /usr/sbin/recovery-mode.sh" >> /tmp/crontab.cron
	fi
	crontab /tmp/crontab.cron
	rm -f /tmp/crontab.cron
}

function stop_cron () {
	log "Stopping crond."
	if [ -f /var/run/crond ]; then
		/sbin/start-stop-daemon -K -p /var/run/crond 2> /dev/null
		rm -f /var/run/crond
		sleep 1
	fi
	killall -9 crond 2> /dev/null
	rm -f /var/run/cron_working
}

case "${1}" in
	start)
		# check if cron is already running.
		if [ ! -z "$(ps | grep "crond" | grep -v "grep")" ]; then
			log "Already running, leaving."
			exit 1
		fi

		start_cron
		setup_cron "on"
		if [ "$(${BEROCONF} get root boot_recoverymode | grep -v failed)" = "1" ]; then
			# if we're starting in recovery-mode, adding reboot sbc in 5min cron task
			setup_cron_recovery "on"
		else
			setup_cron_recovery "off"
		fi
		;;
	stop)
		setup_cron "off"
		setup_cron_recovery "off"
		stop_cron
		;;
	restart)
		${0} stop
		${0} start
		;;
	*)
		echo "Usage: ${0} {start|stop|restart}" >&2
		exit 1
		;;
esac
