#!/bin/sh

enabled="$(uci -q get netmode.global.enabled)"
if [ "$enabled" != "1" ]; then
	exit 0
fi

opconf_file="/opconf/opconf.json"
[ -f $opconf_file ] || opconf_file="/usr_data/opconf/opconf.json"

# Check if netmode getting provisioned from opconf, in case of opconf
# provisioning, mode setting not required
mode="$(jsonfilter -i $opconf_file -e @.netmode.mode 2>/dev/null)"
if [ -n "${mode}" ]; then
	exit 0
fi

# Check if opconf has wan provisioning enabled, if yes, get the proto/mode from opconf
proto="$(jsonfilter -i $opconf_file -e '@.network.wan[@.name="wan"].proto' 2>/dev/null)"
if [ -n "${proto}" ]; then
	mode="routed-${proto}"
	uci -q set netmode.global.mode="${mode}"
	echo "${mode}" > /etc/netmodes/.last_mode
	exit 0
fi

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

if [ ! -f "/etc/netmodes/supported_modes.json" ]; then
	exit 0
fi

# 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
else
	exit 1
fi
