#!/bin/sh

enabled="$(uci -q get netmode.global.enabled)"
[ "$enabled" == "1" ] || exit 0

mode="$(uci -q get netmode.global.mode)"
wanproto=$(uci -q get network.wan.proto)

if [ -n "$mode" ]; then
	# check if wanproto and mode aligned
	if [ "${mode}" = "routed-${wanproto}" ]; then
		exit 0
	fi
fi

[ -f /etc/netmodes/supported_modes.json ] || exit 0

# NetMode is enabled without a Mode being set
# Figure out the current mode from network config
curmode=""
case "$wanproto" in
	dhcp) curmode="routed-dhcp" ;;
	pppoe) curmode="routed-pppoe" ;;
	static) curmode="routed-static" ;;
esac

found=0
for md in $(jsonfilter -i /etc/netmodes/supported_modes.json -e "@.supported_modes.*.name"); do
	[ "$md" == "$curmode" ] && found=1
done

if [ $found -eq 1 ]; then
	uci -q set netmode.global.mode="$curmode"
	echo "$curmode" > /etc/netmodes/.last_mode
fi
