#!/bin/sh
# wizard.cgi — Web endpoint for the one-button setup wizard.
# GET  ?action=status  → returns connectivity state (plain text)
# POST                 → runs the setup wizard, returns output

echo "Content-Type: text/plain"
echo ""

METHOD="${REQUEST_METHOD:-GET}"
ACTION=$(echo "${QUERY_STRING:-}" | grep -o 'action=[^&]*' | cut -d= -f2)

if [ "$METHOD" = "GET" ] && [ "$ACTION" = "status" ]; then
	echo "=== kit-connect Status ==="
	echo ""

	DEVICE_ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname)
	echo "Device:     ${DEVICE_ID}"

	PID=$(cat /var/run/kitconnect/daemon.pid 2>/dev/null || echo "")
	if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
		echo "Daemon:     running (PID ${PID})"
	else
		echo "Daemon:     stopped"
	fi

	TUNNEL_PID=$(cat /var/run/kitconnect/tunnel.pid 2>/dev/null || echo "")
	if [ -n "$TUNNEL_PID" ] && kill -0 "$TUNNEL_PID" 2>/dev/null; then
		echo "Tunnel:     active (PID ${TUNNEL_PID})"
	else
		echo "Tunnel:     not connected"
	fi

	PORT=$(uci -q get kitconnect.main.tunnel_remote_port 2>/dev/null || echo "pending")
	echo "Hub port:   ${PORT}"

	HUB=$(uci -q get kitconnect.main.hub_host 2>/dev/null || echo "unknown")
	echo "Hub host:   ${HUB}"

	if command -v tailscale >/dev/null 2>&1; then
		TS_IP=$(tailscale ip -4 2>/dev/null || echo "unknown")
		echo "Tailscale:  ${TS_IP}"
	else
		echo "Tailscale:  not installed"
	fi

	echo ""
	echo "Config:"
	uci -q show kitconnect 2>/dev/null | while IFS='=' read -r key val; do
		printf "  %-25s = %s\n" "${key##*.}" "${val//\'/}"
	done

	exit 0
fi

if [ "$METHOD" = "POST" ]; then
	/usr/sbin/connect-wizard.sh --force 2>&1
	exit $?
fi

echo "Usage: GET ?action=status  or  POST to run wizard"
