#!/bin/sh
# x5925-boot.sh — Boot persistence stopgap for x5925
# Brings up Tailscale + reverse SSH tunnel on reboot.
# Runs as a Synology scheduled trigger-on-boot task.
# Once the SPK daemon is fixed, this script becomes redundant.

LOG_TAG="kit-connect-boot"
log() { logger -t "$LOG_TAG" -p local0.warn "$*"; }

log "=== Boot persistence for x5925 ==="
log "device=x5925 hub=162.243.83.36 port=2230"

# ── 1. Tailscale ────────────────────────────────────────────────
TAILSCALE_BIN="/usr/local/bin/tailscale"
TAILSCALED_BIN="/usr/local/bin/tailscaled"
TAILSCALE_STATEDIR="/var/packages/Tailscale/var/state"
TAILSCALE_SOCKET="/var/packages/Tailscale/var/run/tailscaled.sock"
AUTH_KEY="tskey-auth-kJz8wqNVo211CNTRL-GNL5EFjp5aWQcaWPSVn2aW9TNworKUNBV"

if [ -x "$TAILSCALED_BIN" ]; then
	mkdir -p "$TAILSCALE_STATEDIR" "$(dirname "$TAILSCALE_SOCKET")"

	# Check if already running
	if "$TAILSCALE_BIN" --socket="$TAILSCALE_SOCKET" status >/dev/null 2>&1; then
		log "tailscale: already connected — $("$TAILSCALE_BIN" --socket="$TAILSCALE_SOCKET" ip -4 2>/dev/null || echo no-ip)"
	else
		log "tailscale: starting tailscaled..."
		/usr/bin/setsid "$TAILSCALED_BIN" \
			--statedir="$TAILSCALE_STATEDIR" \
			--tun=userspace-networking \
			--socket="$TAILSCALE_SOCKET" \
			>/dev/null 2>&1 &
		sleep 4

		log "tailscale: authenticating..."
		"$TAILSCALE_BIN" --socket="$TAILSCALE_SOCKET" up \
			--auth-key "$AUTH_KEY" \
			--hostname x5925 \
			--accept-routes=false \
			--accept-dns=false 2>&1 | while read -r line; do log "tailscale: $line"; done

		ts_ip=$("$TAILSCALE_BIN" --socket="$TAILSCALE_SOCKET" ip -4 2>/dev/null || echo "unknown")
		log "tailscale: connected — IP=${ts_ip}"
	fi
else
	log "tailscale: binaries not found at $TAILSCALED_BIN"
fi

# ── 2. Reverse SSH tunnel ───────────────────────────────────────
TUNNEL_KEY="/var/packages/kit-connect/target/bin/connect_id_ed25519"
TUNNEL_HOST="162.243.83.36"
TUNNEL_USER="node"
TUNNEL_PORT="2230"
LOCAL_SSH_PORT="2223"

if [ -f "$TUNNEL_KEY" ]; then
	chmod 600 "$TUNNEL_KEY"

	# Check if tunnel already exists
	if pgrep -f "ssh.*-R.*${TUNNEL_PORT}" >/dev/null 2>&1; then
		log "tunnel: already active on port ${TUNNEL_PORT}"
	else
		log "tunnel: opening R:0.0.0.0:${TUNNEL_PORT} -> 127.0.0.1:${LOCAL_SSH_PORT}"

		ssh \
			-o StrictHostKeyChecking=no \
			-o UserKnownHostsFile=/dev/null \
			-o ServerAliveInterval=15 \
			-o ServerAliveCountMax=3 \
			-o ExitOnForwardFailure=yes \
			-o BatchMode=yes \
			-p 22 -N \
			-R "0.0.0.0:${TUNNEL_PORT}:127.0.0.1:${LOCAL_SSH_PORT}" \
			-i "$TUNNEL_KEY" \
			"${TUNNEL_USER}@${TUNNEL_HOST}" \
			2>/var/packages/kit-connect/target/var/boot-tunnel.err &

		TUNNEL_PID=$!
		log "tunnel: SSH PID=${TUNNEL_PID}"
		echo "$TUNNEL_PID" > /var/packages/kit-connect/target/var/boot-tunnel.pid
	fi
else
	log "tunnel: key not found at $TUNNEL_KEY"
fi

log "=== Boot persistence complete ==="
