#!/bin/sh

. /lib/cron_utils.sh

blimit=$(uci get limit.bandwidth.enable)
enable=$(uci get monitor.bandwidth.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 "wrtbwmon"
fi

if [ "$blimit" -eq 0 ]; then
	remove_job "wrtbwlimits"
fi

#if [ "$enable" -eq 0 ] && [ "$blimit" = "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 [ "$blimit" -eq 1 ]; then

	# Clear old old values
	remove_job "wrtbwlimits"

	# Defaults
	add_job "*/1 * * * *" "/bin/sh /etc/wrtbwlimits update"
	add_job "*/1 * * * *" "/bin/sh /etc/wrtbwlimits blimit"

	# min hr day_of_mon month day_of_week /usr/sbin/update-motd
	# http://www.corntab.com/pages/crontab-gui

	blimitreset=$(uci get limit.bandwidth.resetenable)
	if [ "$blimitreset" -eq 1 ]; then
		month=$(uci -q get limit.bandwidth.month)
		day=$(uci -q get limit.bandwidth.day)
		hour="*"

		if [[ "$day" == "*" -a "$month" == "*" ]]; then
			hour="*/23"
		fi

		add_job "* $hour $day $month *" "/bin/sh /etc/wrtbwlimits reset"
	fi
	if [ "$enable" -ne 1 ]; then
		/etc/init.d/cron enable
		/etc/init.d/cron restart
	fi
fi

remote=$(uci get agent.agent.enabled)
if [ "$enable" -eq 1 ]; then
	# Clear old old values
	remove_job "wrtbwmon"

	# Some defaults
	add_job "*/1 * * * * /etc/wrtbwmon setup br-lan"

	ULIMIT=$(uci -q get userlimits.global.enabled)
	#if [ $ULIMIT = "1" ]; then
	#	echo "*/5 * * * * /etc/wrtbwmon cap" >> /etc/crontabs/root
	#fi

	if [ "$remote" -eq 1 ]; then
		add_job "*/2 * * * * /etc/wrtbwmon update /tmp/usage.db"
	else
		if [ $ULIMIT -eq 1 ]; then
			add_job "*/2 * * * * /etc/wrtbwmon updateandcap"
		else
			add_job "*/2 * * * * /etc/wrtbwmon update /tmp/usage.db"
		fi
	fi

	# add_job "*/3 * * * * /etc/wrtbwmon publish /tmp/usage.db /tmp/www/usage.htm /etc/macmap.txt"
	add_job "*/3 * * * * /etc/wrtbwmon mydata /tmp/usage.db /www/mydata.htm /etc/macmap.txt"
	add_job "*/4 * * * * /etc/wrtbwmon backup /tmp/usage.db /etc/config/usage.db"

	month=$(uci -q get monitor.bandwidth.month)
	day=$(uci -q get monitor.bandwidth.day)
	hour="*"

	if [[ "$day" == "*" -a "$month" == "*" ]]; then
		hour="*/23"
	fi
	add_job "* $hour $day $month * /etc/wrtbwmon reset /tmp/usage.db /etc/config/usage.db"

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

/etc/wrtbwmon updateandcap 2>&1 >/dev/null &
