#!/bin/sh

. /lib/functions.sh 
. /usr/lib/portal_mgmt/portal_status.sh

[ -n "$VNET_BOOTING" ] && exit 0

[ -z "$INTERFACE" -o "$INTERFACE" = "vwan" ] && exit 0

local under_controller="0"
local isCsMng=`cat /etc/config/controller.conf | grep csId | grep c21f969b5f03d33d43e04f8f136e7682 | wc -l`
if [ ${isCsMng} -le 0 ] ; then
	under_controller="1"
fi
[ "$under_controller" != "1" ] && exit 0

config_load vnetwork
config_get portal "$INTERFACE" "portal"
config_get vlanid "$INTERFACE" "vlanid"
config_get vlans    "$INTERFACE" "vlans"
config_get authType "$INTERFACE" "authType"
config_get ifname   "$INTERFACE" "ifname"
config_get httpsRedirect "$INTERFACE" "httpsRedirect"

NGINX_BIN=/usr/sbin/nginx
NGINX_CONFIG=/etc/portal_mgmt/nginx.conf

portal_mgmt_all()
{
	local cfg="$1"
	[ "$cfg" = "vwan" ] && {
		return 0
	}
	
	config_get portal "$cfg" "portal"
	config_get vlanid "$cfg" "vlanid"
	config_get vlans  "$cfg" "vlans"
	config_get authType "$cfg" "authType"
	config_get ifname   "$cfg" "ifname"
	config_get httpsRedirect "$cfg" "httpsRedirect"
	
	if [ "$portal" == "1" ]; then
		try_to_start_daemon
		
		if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
			portal_mgmt addrule $vlans $authType $httpsRedirect $ifname
		else
			portal_mgmt addrule $vlanid $authType $httpsRedirect VLAN
		fi 
	else
		if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
			portal_mgmt delrule $vlans $ifname 
		else
			portal_mgmt delrule $vlanid VLAN
		fi
	fi
}

case "$ACTION" in
	add)
		if [ "$portal" == "1" ]; then
			try_to_start_daemon

			if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
				portal_mgmt addrule $vlans $authType $httpsRedirect $ifname
			else
				portal_mgmt addrule $vlanid $authType $httpsRedirect VLAN
				
			fi 
		else
			if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
				portal_mgmt delrule $vlans $ifname
			
			else
				portal_mgmt delrule $vlanid VLAN
			fi
			try_to_stop_daemon
			
		fi
		;;
	delete)
		if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
			portal_mgmt delrule $vlans $ifname
		else
			portal_mgmt delrule $vlanid VLAN
		fi
		try_to_stop_daemon

		;;
	
	notify)
		if [ "$portal" == "1" ]; then
			try_to_start_daemon

			if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
				portal_mgmt delrule $vlans $ifname
			else
				portal_mgmt addrule $vlanid $authType $httpsRedirect VLAN
			fi 
		else
			if [ x$vlanid == "x" ] && [ x$vlans != "x" ]; then
				portal_mgmt delrule $vlans $ifname
			else
				portal_mgmt delrule $vlanid VLAN
			fi
			try_to_stop_daemon

		fi
		;;
	commit)
		
		config_foreach portal_mgmt_all vinterface
		try_to_stop_daemon

		;;
esac
