#!/bin/sh

map_bh_file="/var/run/multiap/multiap.backhaul"

# Exit if AL Bridge is not configured to be a bridge device
al_bridge="$(uci -q get mapagent.agent.al_bridge)"
[ "${al_bridge:0:3}" = "br-" ] || exit 0

# Get all sections where the port appears in 'ports' list
port_bridge_sec_list="$(uci show network | grep -w $PORT | grep '\.ports' | cut -d'.' -f2)"

# Find the first section with type='bridge' and get its name
for port_bridge_sec in $port_bridge_sec_list; do
	if [ "$(uci -q get network.$port_bridge_sec.type)" = "bridge" ]; then
		port_bridge_name="$(uci -q get network.$port_bridge_sec.name)"
		break
	fi
done

# Exit if the PORT Bridge Name is empty
[ -z "$port_bridge_name" ]  && exit 0

# Exit if the PORT is not member of the AL Bridge
[ "$port_bridge_name" = "$al_bridge" ] || exit 0

# Exit if the device is not operating in extender/repeater mode
al_brnet="${al_bridge:3}"
[ "$(uci -q get network.${al_brnet}.proto)" == "dhcp" ] || exit 0


################ Dedicated ETH WAN Port ################
wanport="$(jsonfilter -i /etc/board.json -e @.network.wan.device)"
if [ -n "$wanport" ]; then
	[ "$wanport" = "$PORT" ] || exit 0
########################################################
else
#################### DHCP Discovery ####################
	if [ "$LINK" = "up" ]; then
		brctl delif $al_bridge $PORT

		udhcpc -qnRoC -i $PORT >/dev/null 2>&1 && dhcp=1

		brctl addif $al_bridge $PORT

		[ $dhcp -eq 1 ] || exit 0
	else
		[ -f $map_bh_file ] || exit 0
		cur_bh="$(jsonfilter -e @.ifname < "$map_bh_file" 2>/dev/null)" || exit 0
		[ "$cur_bh" = "$PORT" ] || exit 0
	fi
########################################################
fi

remove_from_bridge() {
	config_get ifname "$section" ifname
	[ -n "$ifname" ] && brctl delif ${al_bridge} ${ifname}
}

get_network_id() {
	local ifname=$1

	[ -n "$ifname" ] || return
	network_id=$(wpa_cli -i $ifname list_n|tail -n 1 | awk '{print $1}')
	echo ${network_id}
}

update_bstas() {
	section="$1"
	action="$2"

	config_get ifname "$section" ifname
	config_get_bool enabled "$section" enabled 0

	network_id=$(get_network_id $ifname)
	if [ "$action" = "down" ]; then
		wpa_cli -i "$ifname" disconnect > /dev/null 2>&1
		wpa_cli -i "$ifname" disable_network $network_id  > /dev/null 2>&1
#		wpa_cli -i "$ifname" save_config  > /dev/null 2>&1
	elif [ "$action" = "up" ]; then
		[ "$enabled" -eq 0 ] && return
		wpa_cli -i "$ifname" reconnect > /dev/null 2>&1
		wpa_cli -i "$ifname" enable_network $network_id  > /dev/null 2>&1
#		wpa_cli -i "$ifname" save_config  > /dev/null 2>&1
	fi
}

if [ "$LINK" = "up" ]; then
	#touch "$map_bh_file"
	config_load "mapagent"
	config_foreach remove_from_bridge bsta
	config_foreach update_bstas bsta down

	hwaddr="$(ifconfig $PORT | grep -i hwaddr | awk '{print $5}' | awk '{print tolower($0)}')"
	/lib/wifi/multiap set_uplink "eth" "$PORT" "$hwaddr"
else
	/lib/wifi/multiap unset_uplink "eth"
	#rm -f "$map_bh_file"
	config_load "mapagent"
	config_foreach update_bstas bsta up

fi
