#!/bin/sh
. /lib/zone/zone_api.sh

lan_redirect_ip_set="lan_redirect_ip_set"

if [ -z "$2" ] ; then
	PROXY_HTTP_PORT=8088
else
	PROXY_HTTP_PORT=$2
fi

if [ -z "$3" ] ; then
	PROXY_HTTPS_PORT=8043
else
	PROXY_HTTPS_PORT=$3
fi

iptables_add() {
	arg=$(echo $@ | sed -e 's/-I/-C/g')	
	iptables $arg >/dev/null 2>&1
	if [ $? -ne 0 ]; then
       	iptables $@ >/dev/null 2>&1
	fi
}

iptables_del() {
	arg=$(echo $@ | sed -e 's/-D/-C/g')
	iptables $arg >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		iptables $@ >/dev/null 2>&1
	fi
}

# redirect from LAN networks.
add_redirect_rule_list()
{
	local count=0

	ipset destroy "$lan_redirect_ip_set"
	ipset create "$lan_redirect_ip_set" hash:net -exist 2>&1
	
	config_load vnetwork
	
	_ipset_add_ip()
	{
		local ipaddr
		
		config_get ipaddr "$1" ipaddr

		if [ -n "$ipaddr" ]; then
			if [ "$ipaddr" == "169.254.11.22" ]; then
				return 0
			fi

			ipset add "$lan_redirect_ip_set" "$ipaddr"
			count=$(($count+1))
		fi
	}

	config_foreach _ipset_add_ip vinterface	

	if [ "$count" -gt 0 ]; then
		iptables_add -t nat -w -I PREROUTING -m set --match-set "$lan_redirect_ip_set" dst -p tcp --dport 80 -j REDIRECT --to-ports ${PROXY_HTTP_PORT}
        iptables_add -t nat -w -I PREROUTING -m set --match-set "$lan_redirect_ip_set" dst -p tcp --dport 443 -j REDIRECT --to-ports ${PROXY_HTTPS_PORT}
	fi

	return 0
}

case "$1" in
start)
	add_redirect_rule_list
;;
stop)
	iptables_del -t nat -w -D PREROUTING -m set --match-set "$lan_redirect_ip_set" dst -p tcp --dport 80 -j REDIRECT --to-ports ${PROXY_HTTP_PORT}
	iptables_del -t nat -w -D PREROUTING -m set --match-set "$lan_redirect_ip_set" dst -p tcp --dport 443 -j REDIRECT --to-ports ${PROXY_HTTPS_PORT}
	ipset destroy "$lan_redirect_ip_set"
;;
*)
	# do nothing
;;
esac

return 0
