#!/usr/bin/env bash
set -euo pipefail
# Usage: seed-and-launch.sh CHECKOUT EVIDENCE_ROOT SIDE CDP_PORT
checkout=$1
evidence_root=$2
side=$3
cdp_port=$4
mkdir -p "$evidence_root/site" "$evidence_root/project"
cat > "$evidence_root/site/index.html" <<'HTML'
<!doctype html><html><head><title>Preview demo</title></head><body style="font:20px system-ui;padding:24px;background:#fff;color:#111"><h1>Preview demo</h1><p>The local server is running.</p></body></html>
HTML
git init -q "$evidence_root/project"
cd "$checkout"
vp i
(cd apps/desktop && node node_modules/electron/install.js)
# Disable the launcher's stale-process matching for this evidence run and use the VM's GPU settings.
python3 - <<'PY'
p='apps/desktop/scripts/dev-electron.mjs'
s=open(p).read().replace('cleanupStaleDevApps();','/* Evidence harness: no process matching. */')
if 'electronArgs.push("--disable-gpu")' not in s:
    s=s.replace('const launchArgs = devProtocolClient','electronArgs.push("--disable-gpu");\n  const launchArgs = devProtocolClient')
open(p,'w').write(s)
PY
# Keep this process under supervision and stop it after the driver finishes.
export T3CODE_DEV_SEED=0
export XDG_CONFIG_HOME="$evidence_root/$side-config"
export XDG_DATA_HOME="$evidence_root/$side-data"
export T3CODE_DESKTOP_REMOTE_DEBUGGING_PORT="$cdp_port"
# After startup, add the project through the app CLI in another terminal:
# node apps/server/src/bin.ts project add "$evidence_root/project" --title 'Preview demo' --base-dir .t3
# Move the owned Electron window to 0,0 and resize to 1280x900 with xdotool.
# Run proof-driver.cjs with this checkout, CDP port, and Xvfb DISPLAY/XAUTHORITY.
exec headless-desktop vp run dev:desktop
