#!/bin/sh

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

COUNT=1
SUPP_ARGS=1
SUPPORTED_MODE="/etc/netmodes/supported_modes.json"

if [ ! -f "/etc/config/netmode" ]; then
	exit 0
fi

if [ ! -f "${SUPPORTED_MODE}" ]; then
	exit 0
fi

configure_supp_modes_args()
{
	local obj inst name description required value parent type

	obj="${1}"
	inst="${2}"
	parent="${3}"

	if [ -z "${inst}" ]; then
		return 0
	fi

	json_select ${inst}
	json_get_var name name
	json_get_var description description
	json_get_var value value
	json_get_var required required
	json_get_var type type

	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}=supported_args
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.name="${name}"
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.description="${description}"
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.required="${required}"
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.value="${value}"
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.type="${type}"
	uci -q set netmode.${parent}_supprted_args_${SUPP_ARGS}.dm_parent="${parent}"

	json_select ..
	SUPP_ARGS="$((SUPP_ARGS + 1))"
}

configure_supp_modes()
{
	local obj inst name description args

	obj="${1}"
	inst="${2}"

	if [ -z "${inst}" ]; then
		return 0
	fi

	json_select ${inst}
	json_get_var name name
	json_get_var description description

	if [ -d "/etc/netmodes/${name}" ]; then
		uci -q set netmode.mode_${COUNT}=supported_modes
		uci -q set netmode.mode_${COUNT}.name="${name}"
		uci -q set netmode.mode_${COUNT}.description="${description}"
	fi

	SUPP_ARGS=1
	json_for_each_item configure_supp_modes_args supported_args mode_${COUNT}

	json_select ..
	COUNT="$((COUNT + 1))"
}

remove_mode()
{
	uci -q delete netmode.${1}
}

cleanup_modes()
{
	config_load "netmode"
	config_foreach remove_mode supported_modes
}

update_modes()
{
	local mode

	json_init
	json_load_file "${SUPPORTED_MODE}"
	json_get_var mode mode ""

	if [ -n "${mode}" ]; then
		uci -q set netmode.global.mode="${mode}"
	fi


	json_for_each_item configure_supp_modes supported_modes

}

cleanup_modes
update_modes
