#!/bin/sh
# This script is executed as part of the hotplug event with
# HOTPLUG_TYPE=iface, triggered by various scripts when an interface
# is configured (ACTION=ifup) or deconfigured (ACTION=ifdown).  The
# interface is available as INTERFACE, the real device as DEVICE.

. /lib/functions.sh
# . /lib/zone/zone_api.sh
. /lib/remote_mngt/remote_mngt.sh

system=$(uci get vnetwork."${INTERFACE}".system)

[ -n "$VNET_BOOTING" -a "$system" != "1" ] && exit 0

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

case ${ACTION} in
        delete)
                uci -q delete remote_mngt.$INTERFACE
		uci commit
		[ -z "$DELAY_COMMIT" -a -z "$VNET_BOOTING" ] && rmc_update_rej_rule_list
        ;;
        add|update)
                local netmask=$(uci get vnetwork."${INTERFACE}".netmask)
                local ipaddr=$(uci get vnetwork."${INTERFACE}".ipaddr)
                local network=$(ipcalc -n ${ipaddr} ${netmask} | cut -d '=' -f2)
                local prefix=$(ipcalc -p ${ipaddr} ${netmask} | cut -d '=' -f2)

		uci -q delete remote_mngt.$INTERFACE
		sec=$(uci add remote_mngt lan_rsa_rule)
		uci rename remote_mngt.$sec=$INTERFACE
		uci set remote_mngt.$INTERFACE.enabled="on"
		uci set remote_mngt.$INTERFACE.ipaddr="${network}/${prefix}"
		uci commit
		[ -z "$DELAY_COMMIT" -a -z "$VNET_BOOTING" ] && rmc_update_rej_rule_list
        ;;
	commit)
		[ -z "$VNET_BOOTING" ] && rmc_update_rej_rule_list
	;;
esac
