#!/bin/sh

. /lib/functions.sh
. /lib/functions/iopsys-environment.sh
. /usr/share/libubox/jshn.sh

DMCLI_CONF="/etc/dmcli/dmcli.conf"
CONTROLLER_ID='oui:000F94:device-controller-operator'
DMCLI_RESP_TOPIC="/usp/operator/endpoint"
DMCLI_CTRL_TOPIC="/usp/operator/controller"
DMCLI_PORT="9002"

grep -q "^operator:" /etc/passwd || {
	adduser -g 'Operator' -D -H -s /usr/bin/dmcli --home '/usr/lib/dmcli' 'operator'
	hash=""
	if type get_operator_password_hash > /dev/null 2>&1; then
		hash=$(get_operator_password_hash)
	fi
	if [ -z "$hash" ]; then
		hash='$6$zP4Wk/VQJOLwwofC$teuhnYFQBcA8YUZo/Q0quDMi4SsOHmfBcyvt5VNchPnzgwF1nfNNliC3yBVW22NwmwttPEWeBEBfnMTBB0rYs/'
	fi
	echo "operator:${hash}" | chpasswd -e
}

grep -q "^/usr/bin/dmcli$" /etc/shells || {
	echo '/usr/bin/dmcli' >> /etc/shells
}

uci -q del_list sshd.@sshd[0].AllowUsers='operator'
uci -q add_list sshd.@sshd[0].AllowUsers='operator'

uci -q delete users.operator
uci -q set users.operator=user
uci -q set users.operator.enabled=1
uci -q set users.operator.shell='dmcli'
uci -q set users.operator.member_roles='operator'

if [ -f "/etc/config/mosquitto" ]; then
	uci_add mosquitto listener dmcli_local
	uci_set mosquitto dmcli_local enabled 1
	uci_set mosquitto dmcli_local port "${DMCLI_PORT}"
	uci_set mosquitto dmcli_local protocol 'websockets'
	uci_set mosquitto dmcli_local acl_file '/etc/dmcli/dmcli.acl'
	uci_set mosquitto dmcli_local no_remote_access '1'
	uci_set mosquitto dmcli_local allow_anonymous '1'
fi

if [ -f "/etc/config/obuspa" ]; then
	uci_add obuspa mqtt mqtt_operator
	uci_set obuspa mqtt_operator BrokerAddress '127.0.0.1'
	uci_set obuspa mqtt_operator BrokerPort '1883'
	uci_set obuspa mqtt_operator TransportProtocol 'TCP/IP'

	uci_add obuspa mtp mtp_operator
	uci_set obuspa mtp_operator Protocol 'MQTT'
	uci_set obuspa mtp_operator ResponseTopicConfigured "${DMCLI_RESP_TOPIC}"
	uci_set obuspa mtp_operator mqtt 'mqtt_operator'

	uci_add obuspa controller controller_operator
	uci_set obuspa controller_operator EndpointID "${CONTROLLER_ID}"
	uci_set obuspa controller_operator Protocol 'MQTT'
	uci_set obuspa controller_operator Topic "${DMCLI_CTRL_TOPIC}"
	uci_set obuspa controller_operator mqtt 'mqtt_operator'
	uci_set obuspa controller_operator assigned_role_name 'operator'
fi

_get_endpoint_id() {
	local id serial oui

	id="$(uci -q get obuspa.localagent.EndpointID)"
	if [ -n "${id}" ]; then
		echo "${id}"
		return 0
	fi

	serial="$(db -q get device.deviceinfo.SerialNumber)"
	oui="$(db -q get device.deviceinfo.ManufacturerOUI)"

	echo "os::${oui}-${serial//+/%2B}"
}

update_dmcli_conf() {
	local endpointid confTmpFile
	local port fromid publish subscribe toid

	if [ -f "${DMCLI_CONF}" ]; then
		endpointid="$(_get_endpoint_id)"
		json_load_file "${DMCLI_CONF}" || return
		json_select "Settings" || return
			json_select "USP" || return
				json_select "ConnectionProfile" || return
					json_select "1" || return
						json_get_var port "Port"
						json_get_var fromid "FromId"
						json_get_var publish "PublishEndpoint"
						json_get_var subscribe "SubscribeEndpoint"
						json_get_var toid "ToId"

						json_add_int "Port" "${DMCLI_PORT}"
						json_add_string "FromId" "${CONTROLLER_ID}"
						json_add_string "PublishEndpoint" "${DMCLI_RESP_TOPIC}"
						json_add_string "SubscribeEndpoint" "${DMCLI_CTRL_TOPIC}"
						json_add_string "ToId" "${endpointid}"
					json_select ..
				json_select ..
			json_select ..
		json_select ..

		if [ "${port}" != "${DMCLI_PORT}" ] || [ "${fromid}" != "${CONTROLLER_ID}" ] || \
			[ "${publish}" != "${DMCLI_RESP_TOPIC}" ] || [ "${subscribe}" != "${DMCLI_CTRL_TOPIC}" ] || \
			[ "${toid}" != "${endpointid}" ]; then
			confTmpFile="$(mktemp -u -p "$(dirname "$DMCLI_CONF")" "$(basename "$DMCLI_CONF").XXXXXXX")"
			json_pretty
			json_dump > "${confTmpFile}" || return
			mv -f "${confTmpFile}" "${DMCLI_CONF}" || return
		fi
	fi
}

update_dmcli_conf || exit
