#!/bin/sh /etc/rc.common
# kit-connect — Pioneer Bus Fleet connectivity agent
# Manages Tailscale + reverse SSH tunnel to the fleet hub.
# One package, all GL routers. Hub assigns ports and keys.

USE_PROCD=1
START=90

EXTRA_COMMANDS="wizard status"
EXTRA_HELP="  wizard  Run the Keylink IT setup wizard
  status  Show connectivity status"

start_service() {
	procd_open_instance
	procd_set_param command /usr/sbin/connect-daemon.sh
	procd_set_param respawn 3600 5 0   # max 1 respawn/hr, 5s delay, unlimited
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance
}

wizard() {
	/usr/sbin/connect-wizard.sh
}

status() {
	echo "=== kit-connect Status ==="
	echo "Device: $(cat /etc/busrouter/device-id 2>/dev/null || hostname)"
	if [ -f /var/run/kitconnect.pid ] && kill -0 "$(cat /var/run/kitconnect.pid)" 2>/dev/null; then
		echo "Daemon: running (PID $(cat /var/run/kitconnect.pid))"
	else
		echo "Daemon: stopped"
	fi
	uci -q show kitconnect 2>/dev/null | while IFS='=' read -r key val; do
		echo "Config: ${key##*.}=${val//\'/}"
	done
	echo "Tunnel PID: $(cat /var/run/kitconnect-tunnel.pid 2>/dev/null || echo 'none')"
	if command -v tailscale >/dev/null 2>&1; then
		tailscale status 2>/dev/null | head -3
	else
		echo "Tailscale: not installed"
	fi
}
