#!/bin/sh
# connect-register.sh — Standalone hub registration (callable from wizard or cron)
# Usage: connect-register.sh [--force]
# Re-registers even if already assigned when --force is given.

HUB_HOST="162.243.83.36"
HUB_PORT="8080"

DEVICE_ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname | sed 's/[^a-zA-Z0-9_-]//g')
CURRENT_PORT=$(uci -q get kitconnect.main.tunnel_remote_port 2>/dev/null || echo "0")

[ "$1" = "--force" ] && CURRENT_PORT="0"
[ "$CURRENT_PORT" != "0" ] && {
	echo "Already registered (port ${CURRENT_PORT}). Use --force to re-register."
	exit 0
}

echo "Registering device ${DEVICE_ID} with hub ${HUB_HOST}:${HUB_PORT}..."
resp=$(curl -s --connect-timeout 10 --max-time 15 "http://${HUB_HOST}:${HUB_PORT}/api/register/${DEVICE_ID}" 2>/dev/null)

[ -z "$resp" ] && {
	echo "ERROR: Hub unreachable at ${HUB_HOST}:${HUB_PORT}"
	exit 1
}

port=$(echo "$resp" | grep -o '"tunnel_port"[[:space:]]*:[[:space:]]*[0-9]*' | grep -o '[0-9]*')
status=$(echo "$resp" | grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)
tskey=$(echo "$resp" | grep -o '"tailscale_auth_key"[[:space:]]*:[[:space:]]*"[^"]*"' | cut -d'"' -f4)

echo ""
echo "  Device:  ${DEVICE_ID}"
echo "  Status:  ${status:-unknown}"
echo "  Port:    ${port:-none}"
echo ""

if [ -n "$port" ] && [ "$port" != "0" ]; then
	uci set kitconnect.main.tunnel_remote_port="$port"
	uci commit kitconnect
	echo "Port ${port} saved to UCI config."
fi

if [ -n "$tskey" ]; then
	uci set kitconnect.main.tailscale_auth_key="$tskey"
	uci commit kitconnect
	echo "Tailscale auth key updated from hub."
fi

if [ "$status" = "new" ]; then
	echo ""
	echo "============================================"
	echo "  ✓ Device registered successfully!"
	echo "  Port ${port} assigned for reverse SSH."
	echo "  Restart kit-connect to apply:"
	echo "    /etc/init.d/kitconnect restart"
	echo "============================================"
elif [ "$status" = "existing" ]; then
	echo "✓ Device was already registered (existing assignment confirmed)."
fi
