#!/bin/sh
# /usr/libexec/rpcd/shater — rpcd exec plugin backing luci-app-shater.
#
# Registers the ubus object "shater" (object name == this file's name) with two
# read-side methods the thin LuCI launcher calls over ubus:
#
#   status      -> passthrough of `shaterd status` ({running,enabled,active,table,hash})
#   mint_token  -> passthrough of `shaterd mint-token` ({"token":"..."} | {"error":"..."})
#
# Why shell out to shaterd instead of talking to /var/run/shaterd.ctl directly:
# a reliable AF_UNIX client is NOT guaranteed on stock OpenWrt (busybox `nc` is
# usually built without `-U`; socat/ucode-socket aren't in the base image). shaterd
# already carries the control-socket client, so a tiny `shaterd mint-token` verb is
# the robust, dependency-free bridge. See docs-shater/ARCHITECTURE.md §2.
#
# rpcd exec contract (see the openwrt-ubus-rpcd skill):
#   `<script> list`          -> print ONE JSON object mapping method -> arg signature
#   `<script> call <method>` -> args JSON on stdin (unused here); print JSON reply on stdout
# busybox ash only — no bashisms.

SHATERD=/usr/bin/shaterd

# emit <cmd...> output only if it looks like a JSON object, else a JSON error so the
# caller (LuCI rpc.declare) ALWAYS receives a parseable object, never a blank/garbage
# reply that would register as an empty ubus result.
emit_json() {
	out=$("$@" 2>/dev/null)
	case "$out" in
		'{'*) printf '%s\n' "$out" ;;
		*)    printf '{"error":"shaterd unavailable"}\n' ;;
	esac
}

case "$1" in
	list)
		# Both methods take no arguments.
		echo '{ "status": {}, "mint_token": {} }'
		;;
	call)
		case "$2" in
			status)
				emit_json "$SHATERD" status
				;;
			mint_token)
				emit_json "$SHATERD" mint-token
				;;
			*)
				echo '{"error":"unknown method"}'
				;;
		esac
		;;
esac
