#!/bin/sh
# Thuum Stats — a device recipe in plain shell: curl and jq.
#
#   STATS_URL=https://stats.thuum.dev sh stats-report.sh claim ABCD-EFGH   # once: saves the secret
#   sh stats-report.sh report temp=4.2 door=closed                       # any time after
#
# The secret is saved in $STATS_SECRET_FILE (default ~/.thuum-stats-secret) and STATS_URL beside
# it. A report sets each property on the thing (State Broker: its live value, with its age), then
# publishes them all as one event `reading` on its history (Event Broker). Numbers, true/false
# and null-free JSON are sent as JSON; anything else as text.
set -eu

SECRET_FILE=${STATS_SECRET_FILE:-$HOME/.thuum-stats-secret}

case "${1:-}" in
claim)
	[ -n "${2:-}" ] || { echo "usage: STATS_URL=… sh $0 claim CODE" >&2; exit 1; }
	: "${STATS_URL:?set STATS_URL}"
	body=$(jq -n --arg code "$2" '{code: $code}')
	answer=$(curl -sS -X POST "$STATS_URL/device/claim" -H 'content-type: application/json' -d "$body")
	secret=$(printf '%s' "$answer" | jq -r '.secret // empty' 2>/dev/null || true)
	[ -n "$secret" ] || { echo "claim failed: $answer" >&2; exit 1; }
	umask 077
	printf '%s\n%s\n' "$secret" "$STATS_URL" >"$SECRET_FILE"
	echo "claimed; secret saved in $SECRET_FILE"
	;;
report)
	shift
	[ "$#" -gt 0 ] || { echo "usage: sh $0 report key=value [key=value…]" >&2; exit 1; }
	secret=$(sed -n 1p "$SECRET_FILE")
	STATS_URL=${STATS_URL:-$(sed -n 2p "$SECRET_FILE")}
	grant=$(curl -sS -X POST "$STATS_URL/device/token" -H "authorization: Bearer $secret" \
		-H 'content-type: application/json' -d '{}')
	token=$(printf '%s' "$grant" | jq -r '.token // empty' 2>/dev/null || true)
	[ -n "$token" ] || { echo "no token: $grant" >&2; exit 1; }
	api=$(printf '%s' "$grant" | jq -r .api_url)
	domain=$(printf '%s' "$grant" | jq -r .domain)
	state=$(printf '%s' "$grant" | jq -r .state_topic)
	history=$(printf '%s' "$grant" | jq -r .history_topic)

	data='{}'
	for pair in "$@"; do
		key=${pair%%=*}
		raw=${pair#*=}
		value=$(printf '%s' "$raw" | jq -c . 2>/dev/null || jq -n --arg v "$raw" '$v')
		curl -sS -o /dev/null -w "$key: %{http_code}\n" -X PUT \
			"$api/api/$domain/state/data/$state/$key" \
			-H "authorization: Bearer $token" -H 'content-type: application/json' \
			-d "{\"value\":$value}"
		data=$(printf '%s' "$data" | jq -c --arg k "$key" --argjson v "$value" '. + {($k): $v}')
	done
	curl -sS -o /dev/null -w "reading: %{http_code}\n" -X POST \
		"$api/api/$domain/event/data/$history" \
		-H "authorization: Bearer $token" -H 'content-type: application/json' \
		-d "{\"type\":\"reading\",\"data\":$data}"
	;;
*)
	echo "usage: sh $0 claim CODE | report key=value [key=value…]" >&2
	exit 1
	;;
esac
