#!/bin/sh
# serve-dashboard.sh — Lightweight HTTP server for the kit-connect dashboard.
# Uses busybox httpd, serves on port 8089.
# Started by start-stop-status alongside the main daemon.

PKG_DIR="/var/packages/kit-connect/target"
WWW_DIR="${PKG_DIR}/www"
CGI_DIR="${PKG_DIR}/www/cgi-bin"
PID_FILE="${PKG_DIR}/var/dashboard.pid"
PORT="${1:-8089}"

mkdir -p "$CGI_DIR" "$PKG_DIR/var"

# ── Write busybox httpd config ──────────────────────────────────
cat > "$PKG_DIR/var/httpd.conf" <<EOF
# kit-connect dashboard httpd config
*.html:text/html
*.css:text/css
*.js:text/javascript
*.json:application/json
EOF

# ── Link CGI scripts to www/cgi-bin/ ───────────────────────────
# Status endpoint
cat > "$CGI_DIR/kitconnect-status" << 'CGIEOF'
#!/bin/sh
printf "Content-Type: application/json\r\n\r\n"

DEVICE_ID="unknown"
DAEMON_RUNNING="false"
TUNNEL_PORT="0"
TAILSCALE_IP=""
HUB_REACHABLE="false"

# Device detection
DEVICE_ID=$(cat /etc/busrouter/device-id 2>/dev/null || hostname 2>/dev/null || echo "unknown")

# Daemon check
[ -f /var/packages/kit-connect/target/var/daemon.pid ] && \
  kill -0 "$(cat /var/packages/kit-connect/target/var/daemon.pid)" 2>/dev/null && \
  DAEMON_RUNNING="true"

# Tunnel port from config
TUNNEL_PORT=$(grep '^TUNNEL_REMOTE_PORT=' /etc/kit-connect/connect.conf 2>/dev/null | cut -d= -f2 || echo "0")

# Tailscale
TAILSCALE_IP=$(tailscale ip -4 2>/dev/null || echo "")

# Hub check
HUB_HOST=$(grep '^HUB_HOST=' /etc/kit-connect/connect.conf 2>/dev/null | cut -d= -f2 || echo "162.243.83.36")
HUB_PORT=$(grep '^HUB_PORT=' /etc/kit-connect/connect.conf 2>/dev/null | cut -d= -f2 || echo "8080")
timeout 3 bash -c "echo >/dev/tcp/${HUB_HOST}/${HUB_PORT}" 2>/dev/null && HUB_REACHABLE="true"

printf '{"device_id":"%s","daemon_running":%s,"tunnel_port":"%s","tailscale_ip":"%s","hub_host":"%s","hub_port":"%s","hub_reachable":%s,"config_path":"%s","log_path":"%s"}\n' \
  "$DEVICE_ID" "$DAEMON_RUNNING" "$TUNNEL_PORT" "$TAILSCALE_IP" \
  "$HUB_HOST" "$HUB_PORT" "$HUB_REACHABLE" \
  "/etc/kit-connect/connect.conf" \
  "/var/packages/kit-connect/target/var/connect.log"
CGIEOF
chmod +x "$CGI_DIR/kitconnect-status"

# Wizard endpoint
cat > "$CGI_DIR/kitconnect-wizard" << 'CGIEOF'
#!/bin/sh
printf "Content-Type: text/plain\r\n\r\n"
/var/packages/kit-connect/target/wizard.sh --force 2>&1
CGIEOF
chmod +x "$CGI_DIR/kitconnect-wizard"

# ── Start busybox httpd ────────────────────────────────────────
if command -v busybox >/dev/null 2>&1; then
	# Kill any existing instance
	[ -f "$PID_FILE" ] && kill "$(cat "$PID_FILE")" 2>/dev/null
	rm -f "$PID_FILE"

	busybox httpd -p "$PORT" -h "$WWW_DIR" -c "$PKG_DIR/var/httpd.conf" -v 2>/dev/null &
	echo $! > "$PID_FILE"
	echo "Dashboard started on port ${PORT}"
else
	echo "busybox not available — dashboard not started"
	exit 1
fi
