#!/bin/sh /etc/rc.common
#
# Copyright (C) 2015 OpenWrt-dist
# Copyright (C) 2016 fw867 <ffkykzs@gmail.com>
#
# This is free software, licensed under the GNU General Public License v3.
# See /LICENSE for more information.
#

START=18

add_rule(){
	local action=$2
	local enable macaddr
	config_get_bool enable "$1" enable "0"
	config_get macaddr "$1" macaddr

	if [ -n "$macaddr" -a "$enable" = "1" ]; then
		iptables -t filter -A WEB_RESTRICTION -m mac --mac-source $macaddr -j $action
		[ "$WEB_RESTRICTION_TYPE" = "blacklist" ] && iptables -t nat -A WEB_RESTRICTION -m mac --mac-source $macaddr -j ACCEPT		
	fi
}

webrestriction_header(){
	config_get_bool WEB_RESTRICTION_ENABLE "$1" enable "0"
	config_get WEB_RESTRICTION_TYPE "$1" limit_type "blacklist"
}

start(){
	config_load webrestriction
	config_foreach webrestriction_header basic
	[ "$WEB_RESTRICTION_ENABLE" = "1" ] || return 0

	[ "`iptables -t filter -L forwarding_lan_rule | grep -c WEB_RESTRICTION`" -gt 0 ] && return 0
	iptables -t filter -N WEB_RESTRICTION
	iptables -t filter -F WEB_RESTRICTION
	if [ "$WEB_RESTRICTION_TYPE" = "blacklist" ]; then
		iptables -t nat -N WEB_RESTRICTION
		iptables -t nat -F WEB_RESTRICTION
		config_foreach add_rule macbind DROP
	else
		config_foreach add_rule macbind ACCEPT
		iptables -t filter -A WEB_RESTRICTION -j DROP
	fi

	iptables -t filter -I forwarding_lan_rule -m comment --comment "Rule For Control" -j WEB_RESTRICTION
	[ "$WEB_RESTRICTION_TYPE" = "blacklist" ] && iptables -t nat -I prerouting_lan_rule 1 -m comment --comment "Rule For Control" -j WEB_RESTRICTION
	[ -s "/var/etc/webrestriction.include" ] || echo "/etc/init.d/webrestriction start" > "/var/etc/webrestriction.include"
}

stop(){
	rm -f "/var/etc/webrestriction.include"
	[ "`iptables -t filter -L forwarding_lan_rule | grep -c WEB_RESTRICTION`" -gt 0 ] || return 0
	iptables -t filter -D forwarding_lan_rule -m comment --comment "Rule For Control" -j WEB_RESTRICTION
	iptables -t nat -D prerouting_lan_rule -m comment --comment "Rule For Control" -j WEB_RESTRICTION 2>/dev/null
	iptables -t filter -F WEB_RESTRICTION
	iptables -t filter -X WEB_RESTRICTION
	iptables -t nat -F WEB_RESTRICTION 2>/dev/null
	iptables -t nat -X WEB_RESTRICTION 2>/dev/null
}
