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

rm /tmp/build_exception_subnet_lock 2>/dev/null

build_pptp_l2l_dout_exception_subnet() {
	cat /etc/config/pptp_l2l_dout | grep "config 'pptp-l2l-dout'\|option 'state' 'enable'\|'remotesubnet'" > /tmp/pptp_l2lout_remote_subnet
	
	config_cb()	{
		local cfg="$CONFIG_SECTION"
		local cfgtype
		config_get cfgtype "$cfg" TYPE
		case "$cfgtype" in
			pptp-l2l-dout)
				config_get EN_RULE	$cfg state
				config_get R_SUBNET	$cfg remotesubnet "0.0.0.0"
				
				[ "$EN_RULE" == "enable" -a "$R_SUBNET" != "0.0.0.0" ] && {
					for remotesubnet in $R_SUBNET
					do
						ipset -A exception_subnet_set $remotesubnet
					done
				}
			;;
		esac
	}
	config_load /tmp/pptp_l2lout_remote_subnet
	rm /tmp/pptp_l2lout_remote_subnet
}

build_pptp_l2l_din_exception_subnet() {
	cat /etc/config/pptp_l2l_din | grep "config 'pptp-l2l-din'\|option 'state' 'enable'\|'remotesubnet'" > /tmp/pptp_l2lin_remote_subnet
	
	config_cb()	{
		local cfg="$CONFIG_SECTION"
		local cfgtype
		config_get cfgtype "$cfg" TYPE
		case "$cfgtype" in
			pptp-l2l-din)
				config_get EN_RULE	$cfg state
				config_get R_SUBNET	$cfg remotesubnet "0.0.0.0"
				
				[ "$EN_RULE" == "enable" -a "$R_SUBNET" != "0.0.0.0" ] && {
					for remotesubnet in $R_SUBNET
					do
						ipset -A exception_subnet_set $remotesubnet
					done
				}
			;;
		esac
	}
	config_load /tmp/pptp_l2lin_remote_subnet
	rm /tmp/pptp_l2lin_remote_subnet
}

########################################
### build ipsec exception_subnet_set ###
########################################

ipsec whack --dumpname
cat /etc/config/ipsec_policy | grep "config 'ipsec-rule'\|option 'enable_gre' 'enable'\|list 'more_remotesubnet'\|option 'rightclient'" > /tmp/ipsec_policy_remote_subnet
while read line
do
	right_client=$(uci -q -c /tmp get ipsec_policy_remote_subnet.$line.rightclient)
	if [ "$right_client" != "" -a "$right_client" != "0.0.0.0/32" ]; then
		enable_gre=$(uci -q -c /tmp get ipsec_policy_remote_subnet.$line.enable_gre)
		if [ "$enable_gre" = "enable" ]; then
			ipset -A exception_subnet_gre_set $right_client
			more_remotesubnet=$(uci -q -c /tmp get ipsec_policy_remote_subnet.$line.more_remotesubnet)
			if [ "$more_remotesubnet" != "" ]; then
				for remotesubnet in $more_remotesubnet
				do
					ipset -A exception_subnet_gre_set $remotesubnet
				done
			fi
		else
			ipset -A exception_subnet_set $right_client
			more_remotesubnet=$(uci -q -c /tmp get ipsec_policy_remote_subnet.$line.more_remotesubnet)
			if [ "$more_remotesubnet" != "" ]; then
				for remotesubnet in $more_remotesubnet
				do
					ipset -A exception_subnet_set $remotesubnet
				done
			fi
		fi
	fi
done < "/tmp/whack_connections"
rm /tmp/ipsec_policy_remote_subnet

########################################
### build pptp exception_subnet_set  ###
########################################

build_pptp_l2l_dout_exception_subnet
build_pptp_l2l_din_exception_subnet
