#!/usr/bin/env bash
set -euo pipefail
NAME="${1:?Usage: burnboard-setup.sh NAME [SERVER_URL]}"; SERVER_URL="${2:-https://burnboard-public.vercel.app}"; MODE="${3:-setup}"
command -v node >/dev/null || { echo "Node.js is required." >&2; exit 1; }
INSTALL_DIR="$HOME/.burnboard"; CONFIG="$INSTALL_DIR/config.json"; mkdir -p "$INSTALL_DIR" "$HOME/.claude"
printf '[1/5] Preparing BurnBoard profile...\n'
if [[ -f "$CONFIG" ]] && node -e 'const c=JSON.parse(require("fs").readFileSync(process.argv[1]));process.exit(c.serverUrl===process.argv[2]&&c.token?0:1)' "$CONFIG" "$SERVER_URL"; then
  TOKEN="$(node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1])).token)' "$CONFIG")"
  PROFILE="$(node -e 'const c=JSON.parse(require("fs").readFileSync(process.argv[1]));console.log((c.profileUrl||(`/builder/${process.argv[2].toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"builder"}`)).replace(/^\/intern\//,"/builder/"))' "$CONFIG" "$NAME")"
else
  ENROLLMENT="$(curl -fsS -X POST "$SERVER_URL/api/enroll" -H 'content-type: application/json' --data "$(node -e 'console.log(JSON.stringify({firstName:process.argv[1]}))' "$NAME")")"
  TOKEN="$(node -e 'console.log(JSON.parse(process.argv[1]).token)' "$ENROLLMENT")"; PROFILE="$(node -e 'console.log(JSON.parse(process.argv[1]).profileUrl)' "$ENROLLMENT")"
fi
printf '[2/5] Downloading tracker...\n'; curl -fsS "$SERVER_URL/burnboard-agent.mjs" -o "$INSTALL_DIR/agent.mjs"
node -e 'require("fs").writeFileSync(process.argv[1],JSON.stringify({serverUrl:process.argv[2],token:process.argv[3],profileUrl:process.argv[4]},null,2)+"\n")' "$CONFIG" "$SERVER_URL" "$TOKEN" "$PROFILE"
node - "$HOME/.claude/settings.json" <<'NODE'
const fs=require('fs'),file=process.argv[2],current=fs.existsSync(file)?JSON.parse(fs.readFileSync(file,'utf8')):{};current.env=current.env||{};for(const key of ['CLAUDE_CODE_ENABLE_TELEMETRY','OTEL_METRICS_EXPORTER','OTEL_LOGS_EXPORTER','OTEL_EXPORTER_OTLP_METRICS_PROTOCOL','OTEL_EXPORTER_OTLP_METRICS_ENDPOINT','OTEL_EXPORTER_OTLP_METRICS_HEADERS','OTEL_METRIC_EXPORT_INTERVAL','OTEL_METRICS_INCLUDE_SESSION_ID'])delete current.env[key];fs.writeFileSync(file,JSON.stringify(current,null,2)+"\n");
NODE
printf '[3/5] Scheduling automatic sync...\n'
NODE_BIN="$(command -v node)"; NPX_BIN="$(command -v npx)"
if command -v crontab >/dev/null 2>&1; then
  (crontab -l 2>/dev/null|grep -Ev 'burnboard/agent.mjs|burnboard-cli@latest update'||true;echo "*/5 * * * * $NODE_BIN $INSTALL_DIR/agent.mjs >/dev/null 2>&1";echo "0 4 * * * $NPX_BIN --yes --prefer-online burnboard-cli@latest update >/dev/null 2>&1";echo "@reboot sleep 180 && $NPX_BIN --yes --prefer-online burnboard-cli@latest update >/dev/null 2>&1")|crontab -
  SCHEDULER="cron"
elif command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
  UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"; mkdir -p "$UNIT_DIR"
  cat >"$UNIT_DIR/burnboard-sync.service" <<EOF
[Unit]
Description=BurnBoard token sync
[Service]
Type=oneshot
ExecStart=$NODE_BIN %h/.burnboard/agent.mjs
EOF
  cat >"$UNIT_DIR/burnboard-sync.timer" <<'EOF'
[Unit]
Description=Sync BurnBoard usage every five minutes
[Timer]
OnBootSec=2min
OnUnitActiveSec=5min
AccuracySec=30s
Persistent=true
[Install]
WantedBy=timers.target
EOF
  cat >"$UNIT_DIR/burnboard-update.service" <<EOF
[Unit]
Description=Update BurnBoard tracker
[Service]
Type=oneshot
ExecStart=$NPX_BIN --yes --prefer-online burnboard-cli@latest update
EOF
  cat >"$UNIT_DIR/burnboard-update.timer" <<'EOF'
[Unit]
Description=Check for BurnBoard updates daily
[Timer]
OnBootSec=3min
OnUnitActiveSec=1d
AccuracySec=10min
Persistent=true
[Install]
WantedBy=timers.target
EOF
  systemctl --user daemon-reload
  systemctl --user enable --now burnboard-sync.timer burnboard-update.timer >/dev/null
  SCHEDULER="systemd user timers"
else
  LOOP="$INSTALL_DIR/run-loop.sh"
  cat >"$LOOP" <<EOF
#!/usr/bin/env sh
while :; do
  "$NODE_BIN" "$INSTALL_DIR/agent.mjs" >/dev/null 2>&1
  now=\$(date +%s); last=0; [ -f "$INSTALL_DIR/last-loop-update" ] && last=\$(cat "$INSTALL_DIR/last-loop-update" 2>/dev/null || echo 0)
  if [ \$((now-last)) -ge 86400 ]; then "$NPX_BIN" --yes --prefer-online burnboard-cli@latest update >/dev/null 2>&1 && printf '%s' "\$now" >"$INSTALL_DIR/last-loop-update"; fi
  sleep 300
done
EOF
  chmod 700 "$LOOP"
  if [[ -f "$INSTALL_DIR/loop.pid" ]]; then OLD_PID="$(cat "$INSTALL_DIR/loop.pid" 2>/dev/null || true)"; if [[ -n "$OLD_PID" && -r "/proc/$OLD_PID/cmdline" ]] && tr '\0' ' ' <"/proc/$OLD_PID/cmdline" | grep -q 'run-loop.sh'; then kill "$OLD_PID" 2>/dev/null || true; fi; fi
  nohup "$LOOP" </dev/null >"$INSTALL_DIR/loop.log" 2>&1 & echo $! >"$INSTALL_DIR/loop.pid"
  AUTOSTART_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/autostart"; mkdir -p "$AUTOSTART_DIR"
  cat >"$AUTOSTART_DIR/burnboard.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=BurnBoard Sync
Exec=$LOOP
Terminal=false
X-GNOME-Autostart-enabled=true
EOF
  SCHEDULER="portable background service"
fi
if [[ "$MODE" != "update" ]] && [[ "$(uname -s)" == "Darwin" ]] && ! pgrep -x Antigravity >/dev/null 2>&1 && [[ -d "/Applications/Antigravity.app" ]]; then open -a Antigravity; sleep 8; fi
if [[ "$MODE" != "update" ]] && [[ "$(uname -s)" == "Linux" ]] && ! pgrep -if 'antigravity' >/dev/null 2>&1; then
  ANTIGRAVITY_BIN=""
  for candidate in antigravity antigravity-ide Antigravity; do if command -v "$candidate" >/dev/null 2>&1; then ANTIGRAVITY_BIN="$(command -v "$candidate")"; break; fi; done
  if [[ -n "$ANTIGRAVITY_BIN" ]]; then
    printf 'Starting Antigravity so its local usage service is available...\n'
    nohup "$ANTIGRAVITY_BIN" >/dev/null 2>&1 </dev/null &
    sleep 10
  else
    printf 'Antigravity launcher was not found on PATH. Open Antigravity once, then run: npx --yes burnboard-cli sync\n'
  fi
fi
printf '[4/5] Counting and uploading local history'; OUT="$INSTALL_DIR/setup-sync.out"; ERR="$INSTALL_DIR/setup-sync.err"; node "$INSTALL_DIR/agent.mjs" >"$OUT" 2>"$ERR" & PID=$!
while kill -0 "$PID" 2>/dev/null; do printf '.'; sleep 1; done
if ! wait "$PID"; then printf '\n'; cat "$ERR" >&2; rm -f "$OUT" "$ERR"; exit 1; fi
printf '\n[5/5] Complete\n'; cat "$OUT"; rm -f "$OUT" "$ERR"
echo "Burnboard is connected: $SERVER_URL$PROFILE"; echo "Codex, Claude Code, Cursor, and both supported Antigravity installations sync every 5 minutes using $SCHEDULER. Burnboard checks for updates daily."
