#!/bin/bash
# E2E GUI harness — runs INSIDE the rcbuild container.
# Usage: gui-e2e.sh start | shot NAME | type TEXT | key KEYS | click X Y | stop
set -e
# The container runs as root but the toolchain and caches live in the
# invoking user's home; override with HOME=... if yours differs.
export HOME=${HOME:-/root}
export DISPLAY=:99
export WEBKIT_DISABLE_COMPOSITING_MODE=1
export WEBKIT_DISABLE_DMABUF_RENDERER=1
# Derived from this script's own location (CambiumClient/scripts/) so the
# harness has no machine-specific paths baked in.
CLIENT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RC="$(cd "$CLIENT/.." && pwd)"
SERVER="$RC/CambiumServer"
OUT=${GUI_E2E_OUT:-$HOME/gui-e2e}
# The crates share one workspace target dir at the CambiumClient root — the
# binary has not been under TauriClient/src-tauri/target since src-tauri
# joined the cargo workspace.
APP=$CLIENT/target/release/cambium-desktop

case "$1" in
  start)
    mkdir -p "$OUT"
    pkill -f 'Xvfb :99' 2>/dev/null || true
    Xvfb :99 -screen 0 1400x900x24 &> "$OUT/xvfb.log" &
    sleep 1
    # Testing servers never run inside the codebase — first boot creates
    # Database/ (accounts, TLS keypair) beside server.py, and the tree is
    # source only (see Documentation/RepositoryHygieneAndShipping.md). Boot a
    # copy under $OUT instead; its Database/ persists there across runs.
    mkdir -p "$OUT/server"
    rm -rf "$OUT/server/server.py" "$OUT/server/utilities"
    cp "$SERVER/server.py" "$SERVER/serverconfig.conf" "$OUT/server/"
    cp -r "$SERVER/utilities" "$OUT/server/utilities"
    rm -rf "$OUT/server/utilities/__pycache__"
    (cd "$OUT/server" && python3 server.py &> "$OUT/server.log" & echo $! > "$OUT/server.pid")
    sleep 1
    dbus-run-session -- "$APP" &> "$OUT/app.log" &
    sleep 6
    xdotool search --name "Cambium" windowactivate 2>/dev/null || true
    echo "started; windows:"; xdotool search --name "" getwindowname %@ 2>/dev/null | head -5
    ;;
  shot)
    import -window root "$OUT/$2.png"; echo "$OUT/$2.png"
    ;;
  type)
    shift; xdotool type --delay 40 "$*"
    ;;
  key)
    shift; xdotool key "$@"
    ;;
  click)
    xdotool mousemove "$2" "$3" click 1
    ;;
  dblclick)
    xdotool mousemove "$2" "$3" click --repeat 2 --delay 120 1
    ;;
  scroll)
    xdotool mousemove "$2" "$3" click --repeat "${4:-5}" 5
    ;;
  stop)
    pkill -f "$APP" 2>/dev/null || true
    # Kill only the server THIS harness started (by pidfile) — a bare
    # pkill -f server.py would take down any other instance on the box.
    [ -f "$OUT/server.pid" ] && kill "$(cat "$OUT/server.pid")" 2>/dev/null || true
    rm -f "$OUT/server.pid"
    pkill -f 'Xvfb :99' 2>/dev/null || true
    echo stopped
    ;;
esac
