#!/bin/sh

# format using "shfmt"

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

SULU_CON_CONFIG="/sulu/presets/connection-config.json"
SULU_ACL_FILE=""
SULU_CON_ROLES=""

slog() {
	echo "$*" | logger -t sulu.sh -p debug
}

_get_agent_id() {
	local oui serial endpointid

	endpointid="$(uci_get obuspa localagent EndpointID)"
	if [ -z "${endpointid}" ]; then
		oui="$(db -q get device.deviceinfo.ManufacturerOUI)"
		serial="$(db -q get device.deviceinfo.SerialNumber)"
		echo "${oui}-${serial//+/%2B}"
	else
		endpointid="$(echo "${endpointid/::/,}" | cut -d "," -f 2)"
		endpointid="${endpointid//+/%2B}"
		echo "${endpointid}"
	fi
}

_get_sulu_acl_file() {
	uci -q get mosquitto.sulu.acl_file
}

_sulu_conn_config_users() {
	for user in ${SULU_CON_ROLES}; do
		json_add_object "${user}"
		json_add_string 'fromId' "self::sulu-${user}"
		json_add_string 'publishEndpoint' "/usp/$(_get_agent_id)/${user}/endpoint"
		json_add_string 'subscribeEndpoint' "/usp/$(_get_agent_id)/${user}/controller"
		json_close_object
	done
}

generate_sulu_conn_config() {
	json_init
	json_add_string 'Current-connection' 'main'
	json_add_object 'Connections'
	{
		json_add_object 'main'
		{
			json_add_string 'toId' "os::$(_get_agent_id)"
			json_add_string 'port' "auto"
			json_add_string 'path' "/wss"
			json_add_string 'protocol' 'autoWs'

			json_add_object 'overrides'
			{
				_sulu_conn_config_users
				json_close_object
			}
			json_close_object
		}
		json_close_object
	}
	json_dump >"${SULU_CON_CONFIG}"
}

update_obuspa_config() {
	local agent

	agent="$(_get_agent_id)"
	for user in ${SULU_CON_ROLES}; do
		local section

		# Add mqtt
		section="mqtt_sulu_${user}"
		if ! uci_get obuspa "${section}" >/dev/null 2>&1; then
			uci_add obuspa mqtt "${section}"
			uci_set obuspa "${section}" BrokerAddress "127.0.0.1"
			uci_set obuspa "${section}" BrokerPort "1883"
			uci_set obuspa "${section}" TransportProtocol "TCP/IP"
		fi

		# Add mtp
		section="mtp_sulu_${user}"
		if ! uci_get obuspa "${section}" >/dev/null 2>&1; then
			uci_add obuspa mtp "${section}"
			uci_set obuspa "${section}" Protocol "MQTT"
			uci_set obuspa "${section}" ResponseTopicConfigured "/usp/${agent}/${user}/endpoint"
			uci_set obuspa "${section}" mqtt "mqtt_sulu_$user"
		fi

		# Add controller
		section="controller_sulu_${user}"
		if ! uci_get obuspa "${section}" >/dev/null 2>&1; then
			uci_add obuspa controller "${section}"
			uci_set obuspa "${section}" EndpointID "self::sulu-${user}"
			uci_set obuspa "${section}" Protocol "MQTT"
			uci_set obuspa "${section}" Topic "/usp/${agent}/${user}/controller"
			uci_set obuspa "${section}" mqtt "mqtt_sulu_$user"
			uci_set obuspa "${section}" assigned_role_name "$user"
		fi
	done
}

create_mosquitto_acl() {
	local agentid
	local acl_users

	SULU_ACL_FILE="$(_get_sulu_acl_file)"
	if [ -z "${SULU_ACL_FILE}" ]; then
		return 0
	fi

	echo > "${SULU_ACL_FILE}"
	agentid="$(_get_agent_id)"
	for user in ${SULU_CON_ROLES}; do
		if ! grep -qxF "user $user" "${SULU_ACL_FILE}"; then
			{
				echo "user ${user}"
				echo "topic read  /usp/${agentid}/${user}/controller/reply-to"
				echo "topic write /usp/${agentid}/${user}/endpoint"
				echo "topic read  /usp/${agentid}/${user}/controller"
				echo ""
			} >> "${SULU_ACL_FILE}"
		fi
	done
	chown mosquitto:mosquitto "${SULU_ACL_FILE}"
	chmod 640 "${SULU_ACL_FILE}"
}

get_sulu_roles() {
	local sec path_prefix redirect role

	sec="${1}"

	config_get path_prefix "${sec}" path_prefix ""
	config_get redirect "${sec}" redirect ""
	config_get role "${sec}" role ""

	if [ -n "${redirect}" ]; then
		return 0
	fi

	if [ "${path_prefix}" != "/sulu" ]; then
		return 0
	fi

	if [ -n "${role}" ]; then
		SULU_CON_ROLES="${SULU_CON_ROLES} ${role}"
	fi
}

config_load userinterface
config_foreach get_sulu_roles http_access

generate_sulu_conn_config
create_mosquitto_acl
update_obuspa_config
