#!/bin/sh

. /lib/functions.sh
if [ -f "/usr/local/share/libubox/jshn.sh" ]; then
	. /usr/local/share/libubox/jshn.sh
else
	. /usr/share/libubox/jshn.sh
fi

USERMNGR_DIR="/etc/users/roles"

add_static_roles() {
	local role role_files rname rinst

	role_files="$(ls -1 ${USERMNGR_DIR}/*.json)"

	for role in ${role_files}; do
		json_init
		json_load_file "${role}"
		json_select tr181
		json_get_var rname name
		json_get_var rinst instance

		uci -q set users.role_${rname}=role
		uci -q set users.role_${rname}.enabled="1"
		uci -q set users.role_${rname}.role_id="${rinst}"
		uci -q set users.role_${rname}.name="${rname}"
		uci -q set users.role_${rname}.static="1"
	done
}

remove_invalid_static_roles() {
	local name static

	config_get name "$1" name ""
	config_get_bool static "$1" static "0"

	if [ "${static}" -eq "1" ]; then
		if [ ! -f "${USERMNGR_DIR}/${name}.json" ]; then
			echo "Role file not present, deleting ${1} role"
			uci -q delete users."$1"
		fi
	fi
}

config_load users
config_foreach remove_invalid_static_roles role
add_static_roles

exit 0
