#!/bin/bash
# Nitrous Mission Control — full stack launcher (Tailscale Funnel edition)
# Brings everything back up after a crash:
#   1. Frees port 4000 (kills stale http.server / mc-server.py squatters)
#   2. (Re)starts the mc-server.service systemd unit  (mc-server.py — provides
#      static files + Klaviyo / AWS / GA4 / WhatsApp / watchdog / Woo proxies)
#   3. Ensures tailscaled is running
#   4. Ensures Funnel is enabled and pointing at port 4000
#   5. Opens the PERMANENT public URL in your browser
#   6. Tails mc-server.log so this window shows live server activity

set -u
DIR="/home/sol1/Desktop/MARKETING"
PORT=4000
SERVICE="mc-server.service"
SERVER_LOG="$DIR/mc-server.log"
PUBLIC_URL="https://sol1.tail2d1d46.ts.net/Mission-Control.html"
LOG="/tmp/mission-control-launch.log"
URL_FILE="$DIR/CURRENT_URL.txt"

exec > >(tee -a "$LOG") 2>&1
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  ⌬ NITROUS · Mission Control + Permanent Tunnel"
echo "  $(date '+%Y-%m-%d %H:%M:%S')"
echo "═══════════════════════════════════════════════════════════"
echo ""

cd "$DIR" || { echo "❌ Cannot cd to $DIR"; exit 1; }

# --- 1. Stop the systemd unit + any squatters on port 4000 --------------
echo "▸ Stopping mc-server.service and clearing port $PORT..."
systemctl --user stop "$SERVICE" 2>/dev/null
pkill -f "http.server $PORT"      2>/dev/null && echo "  ✓ killed stale http.server on $PORT"
pkill -f "http.server 3002"       2>/dev/null
pkill -f "$DIR/mc-server.py"      2>/dev/null && echo "  ✓ killed stale mc-server.py"
sleep 2

# --- 2. Force-free the port if something else still has it --------------
if ss -tln 2>/dev/null | grep -q ":$PORT "; then
  echo "  ⚠ Port $PORT still in use — force-freeing..."
  fuser -k -n tcp $PORT 2>/dev/null
  sleep 2
fi

# --- 3. (Re)start mc-server.service via systemd --------------------------
echo "▸ Starting $SERVICE (mc-server.py on $PORT)..."
systemctl --user reset-failed "$SERVICE" 2>/dev/null
systemctl --user restart "$SERVICE"
# wait up to ~10s for the port to come up
for i in $(seq 1 20); do
  if ss -tln 2>/dev/null | grep -q "127.0.0.1:$PORT "; then
    break
  fi
  sleep 0.5
done
if ! ss -tln 2>/dev/null | grep -q "127.0.0.1:$PORT "; then
  echo "❌ mc-server failed to bind $PORT. Last log lines:"
  tail -n 40 "$SERVER_LOG" 2>/dev/null
  echo "    full log: $SERVER_LOG"
  echo "    status:   systemctl --user status $SERVICE"
  exit 1
fi
SERVER_PID=$(systemctl --user show -p MainPID --value "$SERVICE" 2>/dev/null)
echo "  ✓ mc-server.service running (pid ${SERVER_PID:-?}) — Klaviyo / AWS / GA4 / WhatsApp / watchdog proxies live"

# --- 4. Make sure tailscaled is running ----------------------------------
echo "▸ Checking tailscaled..."
if ! systemctl is-active --quiet tailscaled; then
  echo "  ⚠ tailscaled not running — starting it..."
  sudo systemctl start tailscaled
  sleep 3
fi
echo "  ✓ tailscaled active"

# --- 5. Make sure tailscale is logged in ---------------------------------
TS_STATE=$(tailscale status --json 2>/dev/null | python3 -c "import sys,json; print(json.load(sys.stdin).get('BackendState','?'))" 2>/dev/null)
if [ "$TS_STATE" != "Running" ]; then
  echo "  ⚠ Tailscale needs login. Run: sudo tailscale up"
  exit 1
fi
echo "  ✓ Tailscale logged in"

# --- 6. Make sure Funnel is configured for port $PORT --------------------
echo "▸ Checking Funnel..."
FUNNEL_OK=$(sudo tailscale funnel status 2>/dev/null | grep -c "127.0.0.1:$PORT")
if [ "$FUNNEL_OK" -eq 0 ]; then
  echo "  ⚠ Funnel not pointing at $PORT — reconfiguring..."
  sudo tailscale funnel reset 2>/dev/null
  sudo tailscale funnel --bg "$PORT" >/dev/null 2>&1
  sleep 2
fi
echo "  ✓ Funnel on → port $PORT"

# --- 7. Save the URL ------------------------------------------------------
{
  echo "# Last launched: $(date '+%Y-%m-%d %H:%M:%S')"
  echo "# Local:  http://localhost:$PORT/Mission-Control.html"
  echo "# Public: $PUBLIC_URL"
  echo ""
  echo "$PUBLIC_URL"
} > "$URL_FILE"

# Copy to clipboard if available
if command -v xclip >/dev/null 2>&1; then
  printf "%s" "$PUBLIC_URL" | xclip -selection clipboard 2>/dev/null && echo "  ✓ URL copied to clipboard"
elif command -v wl-copy >/dev/null 2>&1; then
  printf "%s" "$PUBLIC_URL" | wl-copy 2>/dev/null && echo "  ✓ URL copied to clipboard"
fi

# --- 8. Open in browser ---------------------------------------------------
echo "▸ Opening browser..."
if command -v xdg-open >/dev/null 2>&1; then xdg-open "$PUBLIC_URL" >/dev/null 2>&1 &
elif command -v firefox >/dev/null 2>&1; then firefox "$PUBLIC_URL" >/dev/null 2>&1 &
elif command -v google-chrome >/dev/null 2>&1; then google-chrome "$PUBLIC_URL" >/dev/null 2>&1 &
fi

# --- 9. Final summary -----------------------------------------------------
echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  ✅  MISSION CONTROL IS LIVE  (permanent URL)"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "  🌐 Public:  $PUBLIC_URL"
echo "  🏠 Local:   http://localhost:$PORT/Mission-Control.html"
echo "  🔑 Login:   admin1234 / mattyp   (or admin / CDrw2211)"
echo ""
echo "  🆔 mc-server pid ${SERVER_PID:-?}  (managed by $SERVICE — auto-restart on crash)"
echo "  Tailscale Funnel runs as a system service — survives reboots."
echo ""
echo "  📋 URL also saved to: $URL_FILE"
echo ""
echo "  Close this window to keep running in the background,"
echo "  or press Ctrl+C to stop the local server (URL goes offline)."
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "  ── live mc-server log ──────────────────────────────────"

trap "echo ''; echo '⏏  Stopping mc-server.service...'; systemctl --user stop $SERVICE 2>/dev/null; exit 0" INT TERM
# Tail the server log so the user sees live activity in this window.
# Closing the window leaves systemd running mc-server.py in the background.
tail -n 20 -F "$SERVER_LOG"
