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

START=99
CONFIG=timecontrol

uci_get_by_type() {
	local index=0
	[ -n $4 ] && index=$4
	local ret=$(uci -q get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

add_rule(){
	local count=$(uci show $CONFIG | grep "@macbind" | sed -n '$p' | cut -d '[' -f 2 | cut -d ']' -f 1)
	[ -n "$count" ] && [ "$count" -ge 0 ] && {
		u_get() {
			local ret=$(uci -q get $CONFIG.@macbind[$1].$2)
			echo ${ret:=$3}
		}
		for i in $(seq 0 $count); do
			local enable=$(u_get $i enable 0)
			local macaddr=$(u_get $i macaddr)
			local timeoff=$(u_get $i timeoff)
			local timeon=$(u_get $i timeon)
			local z1=$(u_get $i z1)
			local z2=$(u_get $i z2)
			local z3=$(u_get $i z3)
			local z4=$(u_get $i z4)
			local z5=$(u_get $i z5)
			local z6=$(u_get $i z6)
			local z7=$(u_get $i z7)
			[ "$z1" == "1" ] && local Z1="Mon,"
			[ "$z2" == "1" ] && local Z2="Tue,"
			[ "$z3" == "1" ] && local Z3="Wed,"
			[ "$z4" == "1" ] && local Z4="Thu,"
			[ "$z5" == "1" ] && local Z5="Fri,"
			[ "$z6" == "1" ] && local Z6="Sat,"
			[ "$z7" == "1" ] && local Z7="Sun"
			if [ -z $enable ] || [ -z $macaddr ] || [ -z $timeoff ] || [ -z $timeon ]; then
				continue
			fi
			if [ "$enable" == "1" ]; then
				iptables -t filter -I TIMECONTROL -m mac --mac-source $macaddr -m time --kerneltz --timestart $timeon --timestop $timeoff --weekdays $Z1$Z2$Z3$Z4$Z5$Z6$Z7 -j DROP
				iptables -t nat -I PREROUTING 1 -m mac --mac-source $macaddr -m time --kerneltz --timestart $timeon --timestop $timeoff --weekdays $Z1$Z2$Z3$Z4$Z5$Z6$Z7 -m comment --comment "TIMECONTROL" -j RETURN
			fi
		done
	}
	echo "/etc/init.d/timecontrol restart" > "/var/etc/timecontrol.include"
}

del_rule(){
	nums=$(iptables -t nat -n -L PREROUTING 2>/dev/null | grep -c "TIMECONTROL")
	if [ -n "$nums" ]; then
		until [ "$nums" = 0 ]
		do
			rules=$(iptables -t nat -n -L PREROUTING --line-num 2>/dev/null | grep "TIMECONTROL" | awk '{print $1}')
			for rule in $rules
			do
				iptables -t nat -D PREROUTING $rule 2>/dev/null
				break
			done
			nums=$(expr $nums - 1)
		done
	fi
}

start(){
	ENABLED=$(uci_get_by_type basic enable 0)
	[ "$ENABLED" != "1" ] && exit 0
	iptables -t filter -N TIMECONTROL
	iptables -t filter -I FORWARD -j TIMECONTROL
	add_rule
}

stop(){
	iptables -t filter -D FORWARD -j TIMECONTROL 2>/dev/null
	iptables -t filter -F TIMECONTROL 2>/dev/null
	iptables -t filter -X TIMECONTROL 2>/dev/null
	del_rule
}
