#!/usr/bin/env bash
# One-time setup: builds vendor/obs-config.js from your existing OBS WebSocket
# plugin config so the overlay/daemon pages can connect.
#
#   bash scripts/setup.sh
#
# Re-run if you change the WebSocket port or password in OBS.
set -euo pipefail

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OBS_DIR="$(cd "$DIR/.." && pwd)"
SRC="$OBS_DIR/plugin_config/obs-websocket/config.json"
OUT="$OBS_DIR/vendor/obs-config.js"

if [[ ! -f "$SRC" ]]; then
  echo "  ✗ $SRC not found." >&2
  echo "    Open OBS once with the obs-websocket plugin loaded so it generates the config." >&2
  exit 1
fi

# Pull port + password out of the JSON
read -r PORT PASS ENABLED <<<"$(python3 -c "
import json, sys
d = json.load(open('$SRC'))
print(d.get('server_port', 4455), d.get('server_password', ''), str(d.get('server_enabled', False)).lower())
")"

mkdir -p "$OBS_DIR/vendor"
cat > "$OUT" <<JS
// Auto-generated by scripts/setup.sh — gitignored. Reflects the current contents
// of plugin_config/obs-websocket/config.json. Re-run scripts/setup.sh if it changes.
window.__OBSWS = {
  url:      'ws://localhost:$PORT',
  password: '$PASS',
};
JS

echo "  ✓ wrote $OUT"
echo "    url      = ws://localhost:$PORT"
if [[ -z "$PASS" ]]; then
  echo "    password = (none)"
else
  echo "    password = (set, ${#PASS} chars)"
fi

# Check the live socket, not the config file — OBS lags writes to plugin_config
# until shutdown, so server_enabled in JSON often disagrees with reality.
echo
if ss -lnt 2>/dev/null | grep -q ":$PORT "; then
  echo "  ✓ OBS WebSocket server is listening on :$PORT"
elif nc -z localhost "$PORT" 2>/dev/null; then
  echo "  ✓ OBS WebSocket server is listening on :$PORT"
else
  echo "  ⚠ Nothing listening on :$PORT yet."
  echo "    In OBS:  Tools → WebSocket Server Settings → ✅ Enable WebSocket server → OK"
  echo "    (config.json may already say 'enabled: $ENABLED' — that file lags actual state)"
fi
