#!/bin/bash
#
# VERSION=10
# CHANGES="Do not start in update-mode."

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

BEROCONF=/usr/fallback/beroconf

CRONBIN=/usr/sbin/crond
CRONDIR=/usr/conf/cron
CRONTAB=${CRONDIR}/root
CRONPID=/var/run/crond
CRONLOG=/var/log/cron.log
CRONWRK=/var/run/cron_working
CRONOPT="-c ${CRONDIR}"

PREFIX="[init_cron]"

function prep_cron {

	if [ ! -d ${CRONDIR} ] ; then
		mkdir -p ${CRONDIR}
	fi

	if [ ! -f ${CRONTAB} ]; then
		echo "*/5 * * * * /bin/touch ${CRONWRK}" > ${CRONTAB}
	elif [ -z "$(grep ${CRONWRK} ${CRONTAB})" ]; then
		echo "*/5 * * * * /bin/touch ${CRONWRK}" >> ${CRONTAB}
	fi
}


if [ "${2}" = "createlog" ]; then
	CRONOPT="-c ${CRONDIR} -l8 -L${CRONLOG}"
fi

case "${1}" in
	start)
		# exit if we're starting in update-mode.
		if [ "$(${BEROCONF} get root boot_fwupdate | grep -v failed)" = "1" ]; then
			exit 0
		fi

		# check if cron is already running.
		cron_running=$(ps -A | grep ${CRONBIN} | grep -v "grep")
		if [ ! -z "${cron_running}" ]; then
			echo "${PREFIX} already running, leaving."
			exit 1
		fi

		prep_cron

		# start crond
		echo -n "${PREFIX} Starting crond: "
		/sbin/start-stop-daemon -S -m -p ${CRONPID} -x ${CRONBIN} -- ${CRONOPT}
		echo "Done."
		;;
	stop)
		# stop crond
		echo -n "${PREFIX} Stopping crond: "
		if [ -f ${CRONPID} ]; then
			/sbin/start-stop-daemon -K -p ${CRONPID} 2> /dev/null
			rm -f ${CRONPID}
			sleep 1
		fi
		killall -9 crond 2> /dev/null
		rm -f ${CRONWRK}
		echo "Done."
		;;
	restart)
		${0} stop
		${0} start
		;;
	*)
		echo "${PREFIX} Usage: ${0} {start|stop|restart}" >&2
		exit 1
		;;
esac
