#!/bin/sh
# connect-register.sh — Standalone hub registration for Synology routers.
# Callable from the wizard, postinst, or manually.
# Usage: connect-register.sh [--force]
#   --force  Re-register even if already assigned

HUB_HOST="162.243.83.36"
HUB_PORT="8080"
CONF="/etc/kit-connect/connect.conf"
FORCE=0
[ "$1" = "--force" ] && FORCE=1

DEVICE_ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname 2>/dev/null | sed 's/[^a-zA-Z0-9_-]//g')
CURRENT_PORT=$(grep '^TUNNEL_REMOTE_PORT=' "$CONF" 2>/dev/null | cut -d= -f2 || echo "0")

[ "$FORCE" = "1" ] && 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=$(printf '%s' "$resp" | sed -n 's/.*"tunnel_port"[[:space:]]*:[[:space:]]*\([0-9]*\).*/\1/p')
status=$(printf '%s' "$resp" | sed -n 's/.*"status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')

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

if [ -n "$port" ] && [ "$port" != "0" ]; then
	sed -i "s/^TUNNEL_REMOTE_PORT=.*/TUNNEL_REMOTE_PORT=${port}/" "$CONF" 2>/dev/null
	echo "Port ${port} saved to ${CONF}."
fi

# Authorize key with hub
TUNNEL_KEY="/var/packages/kit-connect/target/bin/connect_id_ed25519"
if [ -f "$TUNNEL_KEY" ] && [ -n "$port" ]; then
	PUBKEY=$(awk '{print $1" "$2}' "${TUNNEL_KEY}.pub" 2>/dev/null)
	if [ -n "$PUBKEY" ]; then
		curl -s --connect-timeout 10 --max-time 15 \
			-X POST "http://${HUB_HOST}:${HUB_PORT}/api/authorize-key" \
			-H "Content-Type: application/json" \
			-d "{\"device_id\":\"${DEVICE_ID}\",\"pubkey\":\"${PUBKEY}\"}" \
			>/dev/null 2>&1 || true
		echo "Tunnel key sent to hub for authorization."
	fi
fi

if [ "$status" = "new" ]; then echo ""; echo "  ✓ Device registered — restart kit-connect to apply"; fi
