#!/usr/bin/env bash
# Serve the SKAP prototype for viewing from other devices (wraps tools/serve.py).
#
# Usage:
#   tools/serve-prototype.sh            # home Wi-Fi + Tailscale
#   tools/serve-prototype.sh --public   # also Tailscale Funnel: a fixed https link anyone can open
#   PORT=9000 tools/serve-prototype.sh  # custom port
set -euo pipefail

PORT="${PORT:-8765}"
TOOLS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
START_PATH="prototype/map.html"
IS_PUBLIC=false

case "${1:-}" in
  "") ;;
  --public) IS_PUBLIC=true ;;
  -h|--help) sed -n '2,7p' "$0"; exit 0 ;;
  *) echo "Unknown option: $1 (use --public or --help)" >&2; exit 1 ;;
esac

if ss -ltn "sport = :$PORT" | grep -q LISTEN; then
  echo "Port $PORT is already in use. Try: PORT=9000 $0" >&2
  exit 1
fi
if $IS_PUBLIC && ! command -v tailscale >/dev/null; then
  echo "tailscale is not installed, cannot open a public link" >&2
  exit 1
fi

python3 "$TOOLS_DIR/serve.py" --host 0.0.0.0 --port "$PORT" >/dev/null &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT

sleep 0.5
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
  echo "Prototype server failed to start" >&2
  exit 1
fi

LAN_IP="$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{for (i = 1; i < NF; i++) if ($i == "src") print $(i + 1)}')"
TS_IP="$(tailscale ip -4 2>/dev/null || true)"
TS_HOST="$(tailscale status --json 2>/dev/null | python3 -c 'import json, sys; print(json.load(sys.stdin)["Self"]["DNSName"].rstrip("."))' 2>/dev/null || true)"

echo "SKAP prototype is running:"
echo "  This computer: http://localhost:$PORT/$START_PATH"
[[ -n "$LAN_IP" ]] && echo "  Home Wi-Fi:    http://$LAN_IP:$PORT/$START_PATH"
[[ -n "$TS_IP" ]] && echo "  Tailscale:     http://$TS_IP:$PORT/$START_PATH"

if ! $IS_PUBLIC; then
  echo
  echo "Ctrl+C to stop."
  wait "$SERVER_PID"
  exit 0
fi

# Funnel keeps the same address on every run, unlike Cloudflare quick tunnels, whose fresh
# random hostnames take a while to reach public DNS and get cached as "not found" if opened early.
echo "  Public:        https://$TS_HOST/$START_PATH"
echo "  Anyone with the link can open it. Ctrl+C stops everything."
echo
# Runs in the foreground, so Ctrl+C closes the public link together with the server.
if ! tailscale funnel "$PORT"; then
  echo >&2
  echo "Funnel did not start. If it says 'access denied', run once: sudo tailscale set --operator=\$USER" >&2
  exit 1
fi
