#!/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.

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

[ "$DEVICE" == "lo" ] && exit 0

. /lib/functions.sh
. /lib/zone/zone_api.sh
. /lib/imb/core_global.sh
# 针对interface的创建
# 1. 全配置下发(Force Provision): notify NETWORKX + commit null(ZACTION=)
# 2. 预配置下发: notify NETWORK1 + add NETWORKother + commit null(ZACTION=LANX=add LANY=add)
# 3. 增删: add/delete NETWORKX + commit null(ZACTION=LANX=add/delete)
# 4. 更新(部分配置): notify NETWORKX + commit null(ZACTION=)
# 5. 更新(其他配置): delete NETWROKX + add NETWORKX + commit null(ZACTION=LANX=delete,add) 
# 针对vlan的创建
# 1. 增删: add/delete + commit null(ZACTION=)
# 2. 批量删除: delete + delete + ... + commit null(ZACTION=)
# 3. 更新: delete + add + commit null(ZACTION=)

# imb模块和NETWORK耦合的功能主要分为两部分，
# 一是和zone相关的配置，理论上仅在network删除时，需要将这部分配置删除。但在新增和更新时不处理，因此放到commit中操作
# 二是和interface本身相关的配置，包括iptables规则和ipset，由于更新时，可能ip会发生变化，因此需要放到add/delete中操作



case "$ACTION" in
	add)
		fw_imb_event_interface "$INTERFACE" add LAN
	;;
	delete)
		fw_imb_event_interface "$INTERFACE" del LAN
	;;
	commit)
		if [ -n "$ZACTION" ]; then
			for zact in $ZACTION
			do
				zone=${zact%%=*}
				op=${zact##*=}
				option=0
				for act in ${op//,/ }
				do
					[ "$act" == "delete" ] && option=$(($option - 1))
					[ "$act" == "add" ] && option=$(($option + 1))
				done
				[ "$option" == "-1" ] && {
					# 仅在delete场景下需要对imb的config做处理
					imb_zone_config "$zone"
				}
			done
		else
			#do nothing
			return 0
		fi
	;;
	*)
		# (notify) do nothing
	;;
esac
