#!/bin/sh

. /lib/cron_utils.sh

enable=$(uci -q get bwinternal.global.enable)

fix() {
	echo "#Fix" > /etc/crontabs/root
	echo "SHELL=/bin/sh" >> /etc/crontabs/root
	echo "PATH=/etc:/sbin:/bin:/usr/sbin:/usr/bin" >> /etc/crontabs/root
	echo "#End" >> /etc/crontabs/root
}

if [ "$enable" -eq 0 ]; then
	remove_job "bwcurrent.sh"
	remove_job "bwreset_int.sh"
fi

#if [ "$enable" -eq 0 ]; then
#	[ -z "$(ls /etc/crontabs/)" ] && return 1
#	size=$(wc -c < "/etc/crontabs/root")
#	if [ "$size" -lt 2 ]; then
#		/etc/init.d/cron disable
#		/etc/init.d/cron stop
#		rm -rf /etc/crontabs/root
#	fi
#fi

if [ "$enable" -eq 1 ]; then

	# Clear old old values
	remove_job "bwcurrent.sh"
	remove_job "bwreset_int.sh"

	# Defaults
	add_job "*/2 * * * * /etc/bwcurrent.sh"

	reset=$(uci get bwinternal.global.resetenable)
	if [ "$reset" -eq 1 ]; then
		month=$(uci -q get bwinternal.global.month)
		day=$(uci -q get bwinternal.global.day)
		hour="*"

		if [[ "$day" == "*" -a "$month" == "*" ]]; then
			hour="*/23"
		fi
		add_job "* $hour $day $month * /etc/bwreset_int.sh"
	fi

	/etc/init.d/cron enable
	/etc/init.d/cron restart
fi

