#!/bin/sh
# shellcheck disable=SC1090,SC1091
# vim: set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

. /lib/overthebox

otb_save_event start

# This code is really bad and should be removed as soons as possible
id=$(uci -q get overthebox.me.action_id)

if [ -n "$id" ]; then
	otb_todo otb_device_put "actions/$id" -d@- <<-EOF
	{"status":"done"}
	EOF
	uci -q batch <<-EOF
	delete overthebox.me.action_id
	commit overthebox
	EOF
fi

otb_todo otb-action-refreshProperties </dev/null

_run() {
	otb_reload

	otb-check-config
	reload_config

	if [ -z "$OTB_DEVICE_ID" ]; then
		otb-subscribe
		return
	fi

	# todo
	for file in "$OTB_TODO_DIR"/*; do
		[ -f "$file" ] && (. "$file") && rm -f "$file"
	done

	ret=$(otb_device_get actions/todo --dump-header "$OTB_HEADERS_FILE") || {
		sleep 30
		return
	}

	if [ -z "$OTB_SERVICE_ID" ] || [ "$(echo "$ret" | jq -r '.class' 2>/dev/null)" = "Client::Unauthorized" ]; then
		read -r LINE < "$OTB_HEADERS_FILE"
		case "$LINE" in
			HTTP*403*) otb_err "Got 403: resubscribe" ; otb-subscribe ; return ;;
			HTTP*401*) otb_err "Got 401: renewing jwt" ; otb-renew-jwt ; return ;;
		esac
	fi

	action=$(otb_json_get "$ret" action)
	id=$(otb_json_get "$ret" id)
	otb_debug "Got action '$action' with id '$id'"
	[ -z "$action" ] || [ "$action" = "null" ] && return

	# Output in json
	if [ "$action" = "speedtest" ]; then
		details=$(otb-action-"$action" -j 2>&1) && status="done" || status="error"
		otb_debug "Got status '$status' for action '$action'"
		[ -z "$id" ] || [ "$id" = "null" ] || [ "$action" = "wait" ] && return

		# shellcheck disable=SC2016
		jq -c -n --arg status "$status" --arg details "$details" \
			'{status: $status, details: $details}' | otb_device_put "actions/$id" -d@-
	else
		details=$(otb-action-"$action" "$ret" 2>&1) && status="done" || status="error"
		otb_debug "Got status '$status' for action '$action'"

		[ "$action" = "restore" ] && {
			otb_info "Should renew JWT before sending status for action $action"
			otb-renew-jwt
		}

		[ -z "$id" ] || [ "$id" = "null" ] || [ "$action" = "wait" ] && return

		# shellcheck disable=SC2016
		jq -c -n --arg status "$status" --arg details "$details" \
			'{status: $status, details: $details}' | otb_device_put "actions/$id" -d@-
	fi
}

RUNNING=1
trap 'RUNNING=' INT QUIT TERM

while [ "$RUNNING" ]; do
	sleep 1
	_run
done
