#!/bin/bash
# Nitrous Mission Control launcher
# Double-click this file (or: bash Launch-Mission-Control.sh)
cd "$(dirname "$0")"

PORT=3002
URL="http://localhost:$PORT/Mission-Control.html"

# If port busy, increment up to 3010
while lsof -i ":$PORT" >/dev/null 2>&1 && [ $PORT -lt 3010 ]; do
  PORT=$((PORT+1))
  URL="http://localhost:$PORT/Mission-Control.html"
done

echo ""
echo "═══════════════════════════════════════════════════════════"
echo "  ⌬ NITROUS · Mission Control"
echo "═══════════════════════════════════════════════════════════"
echo ""
echo "  ▸ Starting local server on port $PORT..."
python3 -m http.server $PORT --bind 127.0.0.1 >/tmp/mission-control-server.log 2>&1 &
SERVER_PID=$!
sleep 1

echo "  ▸ Opening in browser..."
if command -v xdg-open >/dev/null 2>&1; then xdg-open "$URL" >/dev/null 2>&1
elif command -v open >/dev/null 2>&1; then open "$URL"
elif command -v firefox >/dev/null 2>&1; then firefox "$URL" >/dev/null 2>&1 &
elif command -v google-chrome >/dev/null 2>&1; then google-chrome "$URL" >/dev/null 2>&1 &
else echo "  ⚠ Could not auto-open browser. Visit: $URL"
fi

echo ""
echo "  ✓ Server running. Page open at:"
echo "    $URL"
echo ""
echo "  Default login: admin / CDrw2211"
echo ""
echo "  Press Ctrl+C in this window to stop the server."
echo "═══════════════════════════════════════════════════════════"
echo ""

trap "echo ''; echo '  Stopping server...'; kill $SERVER_PID 2>/dev/null; exit" INT TERM
wait $SERVER_PID
