#!/bin/sh

if ! command -v obuspa >/dev/null 2>&1; then
	exit 0
fi

# source jshn shell library
. /usr/share/libubox/jshn.sh

USP_PATH="/tmp/sulu/"
VERSIONS_PRESET_FILE="/sulu/presets/versions.json"

log() {
	logger -t sulu_watcher "$*"
}

wait_for_obuspa() {
	while true; do
		ENDPOINTID="$(obuspa -c get Device.LocalAgent.EndpointID |grep Device.|awk '{print $3}')"
		sleep 2
		if [ -n "${ENDPOINTID}" ]; then
			break;
		fi
	done
}

extract_versions() {
	IOWRT_VERSION="$(obuspa -c get 'Device.DeviceInfo.FirmwareImage.[Status==Active].Name' | awk '{print $3}')"
	OPCONF_VERSION="$(obuspa -c get 'Device.X_GENEXIS_EU_OpConf.Version' | awk '{print $3}')"

	json_init
	json_pretty
	json_add_object 'versions'
	json_add_string 'firmwareVersion' "$IOWRT_VERSION"
	json_add_string 'opconfVersion' "$OPCONF_VERSION"
	json_close_object
	json_dump > ${VERSIONS_PRESET_FILE}
}

mark_sulu_ready() {
	mkdir -p "${USP_PATH}"
	touch ${USP_PATH}/ready
}

wait_for_obuspa
extract_versions
mark_sulu_ready
