#!/bin/sh
. /etc/functions.sh

set_webfilter() {
	local ENABLE
	local F_TYPE
	local F_URL
	
	config_get_bool ENABLE  $1	enable  0
	if [ $ENABLE -eq 1 ]; then
		config_get F_TYPE $1 type
		config_get F_URL $1	value
		config_get time_obj $1 time_obj -1

		xt_time=""
		trim() { echo $1; }
		[ "$time_obj" == "-1" ] || {		#set time obj
			delete=`uci -q get time_obj.$time_obj.delete || echo 0`
			[ "$delete" == "1" ] && xt_time="" ||
			{
				dstart=`uci -q get time_obj.$time_obj.datestart`
				dstop=`uci -q get time_obj.$time_obj.datestop`
				tsatrt=`uci -q get time_obj.$time_obj.timestart`
				tstop=`uci -q get time_obj.$time_obj.timestop`
				weekdays=`uci -q get time_obj.$time_obj.weekdays`
				xt_time=$(trim "${dstart:+--datestart $dstart} ${dstop:+--datestop $dstop} ${tsatrt:+--timestart $tsatrt} ${tstop:+--timestop $tstop} ${weekdays:+--weekdays $weekdays}")
			}
		}
			
		case "$F_TYPE" in 
		content)
			iptables -A web_filter_rule -p tcp -m tcp --dport 80 -m webstr --content $F_URL \
			${xt_time:+-m time $xt_time --tz $(date +%z | cut -c1-3):$(date +%z | cut -c4-5)} \
			-j REJECT --reject-with tcp-reset
			iptables -A web_filter_rule -p tcp -m tcp --dport 3128 -m webstr --content $F_URL \
			${xt_time:+-m time $xt_time --tz $(date +%z | cut -c1-3):$(date +%z | cut -c4-5)} \
			-j REJECT --reject-with tcp-reset
			iptables -A web_filter_rule -p tcp -m tcp --dport 8080 -m webstr --content $F_URL \
			${xt_time:+-m time $xt_time --tz $(date +%z | cut -c1-3):$(date +%z | cut -c4-5)} \
			-j REJECT --reject-with tcp-reset
		;;
		
		url)
			iptables -A web_filter_rule -p tcp -m tcp -m webstr --url $F_URL \
			${xt_time:+-m time $xt_time --tz $(date +%z | cut -c1-3):$(date +%z | cut -c4-5)} \
			-j REJECT --reject-with tcp-reset
		;;
		
		host)
			iptables -A web_filter_rule -p tcp -m tcp -m webstr --host $F_URL \
			${xt_time:+-m time $xt_time --tz $(date +%z | cut -c1-3):$(date +%z | cut -c4-5)} \
			-j REJECT --reject-with tcp-reset
		;;
		esac

	fi
}

# Add Web filter rule
if [ -f /etc/config/webfilter ]; then
	# delete all rule
	iptables -t filter -F web_filter_rule 2>/dev/null || (iptables -N web_filter_rule; iptables -A forward_csm -j web_filter_rule)

    config_load /etc/config/webfilter
    config_foreach set_webfilter webfilter
	
	# restart HNAT
	/etc/init.d/shnat_cli restart > /dev/null 2>&1
fi