#!/bin/sh /etc/rc.common

START=90

. /lib/functions.sh
. /lib/functions/network.sh

cron_tmp="/tmp/tmp.cron"
network_find_wan wan_if
wan_phy_if=$(uci -P/var/state get network.${wan_if}.ifname)
interface=${wan_phy_if:-eth0.2}

load_modules()
{
	insmod cls_fw >&- 2>&-
	insmod sch_hfsc >&- 2>&-
	insmod sch_esfq >&- 2>&-
	insmod ifb >&- 2>&-
	insmod xt_multiport >&- 2>&-
	insmod cls_u32 >&- 2>&-
	insmod showspeed >&- 2>&-
}

unload_modules()
{
	rmmod showspeed >&- 2>&-
	#rmmod cls_fw >&- 2>&-
	#rmmod sch_hfsc >&- 2>&-
	#rmmod sch_esfq >&- 2>&-
	#rmmod ifb >&- 2>&-
	#rmmod xt_multiport >&- 2>&-
	#rmmod cls_u32 >&- 2>&-	
}

crontabs_set()
{
	config_get type main type
	
	touch /etc/crontabs/root
	grep -v "/etc/init.d/bandwidth restart" /etc/crontabs/root > $cron_tmp
	if [ "$1" = "start" ] ;then
		case "$type" in
			"monthly")
				config_get day main day
				config_get hour main hour
				echo 0 $hour $day \* \* /etc/init.d/bandwidth restart >> $cron_tmp
				;;
			"weekly")
				config_get week main week
				config_get hour main hour
				echo 0 $hour \* \* $week /etc/init.d/bandwidth restart >> $cron_tmp
				;;
			"daily")
				config_get hour main hour
				echo 0 $hour \* \* \* /etc/init.d/bandwidth restart >> $cron_tmp
				;;
			"hourly")
				echo 0 \* \* \* \* /etc/init.d/bandwidth restart >> $cron_tmp
				;;
		esac
	fi
	
	mv $cron_tmp /etc/crontabs/root
	/etc/init.d/cron restart
	
}

stop()
{
	crontabs_set stop
	killall bw >&- 2>&-
	iptables -t mangle -D FORWARD -j bandwidth_forward >&- 2>&-
	iptables -t mangle -F bandwidth_forward >&- 2>&-
	iptables -t mangle -X bandwidth_forward >&- 2>&-	
	
	tc qdisc del dev $interface ingress >&- 2>&-
	tc qdisc del dev $interface root >&- 2>&-
	tc qdisc del dev ifb0 root >&- 2>&-
	#unload_modules
}

start()
{		
	config_load bandwidth
	config_get enabled main enabled

	[ 1 -ne "$enabled" ] && return

	unload_modules
	load_modules
	crontabs_set start
	bw -o $interface >/dev/null &
}

boot()
{
	#Do nothing here.Program is started by Hotplug.
	return 0
}