#!/usr/bin/env bash
# Run captchaforge-bench in headful mode — works cross-platform with
# the same single command:
#   * Linux without a display (CI, server): wraps with `xvfb-run` so
#     real Chrome runs against a virtual X11 display. Required for
#     real-WAF benches because production WAFs (Cloudflare Turnstile,
#     hCaptcha) detect Chrome's `--headless` flag at a depth no JS
#     stealth shim can fully suppress; an actual non-headless Chrome
#     under xvfb is fingerprint-identical to a normal user's Chrome.
#   * Linux with a display, macOS, Windows: runs Chrome directly under
#     the host display. xvfb-run is a no-op on those — but skip
#     the wrapping rather than depending on it being installed.
#
# Usage:
#   tools/run_headful_bench.sh --suite real-waf --with-network --max-concurrent 2
#
# Env passthrough:
#   REAL_WAF_ITERS=N          override iterations per fixture
#   RUST_LOG=warn|info|debug  bench logging level
#   BENCH_HEADFUL=1           also-honored (this script forces it on)
#
# Exit status mirrors the bench binary's.

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BIN="${BIN:-$REPO_ROOT/target/release/captchaforge-bench}"

if [ ! -x "$BIN" ]; then
    echo "Bench binary not built. Run: cargo build --release -p captchaforge-bench" >&2
    exit 2
fi

# Force the headful flag on regardless of caller args; the whole point
# of this wrapper is "I want real Chrome".
ARGS=("--headful" "$@")

case "$(uname -s)" in
    Linux)
        if [ -n "${DISPLAY:-}" ] && [ "${SKIP_XVFB:-0}" = "1" ]; then
            # Real display present + caller opted out of xvfb wrapping.
            echo "[headful] using existing DISPLAY=$DISPLAY (xvfb skipped)" >&2
            exec env BENCH_HEADFUL=1 "$BIN" "${ARGS[@]}"
        elif command -v xvfb-run >/dev/null 2>&1; then
            echo "[headful] linux/no-display: wrapping with xvfb-run" >&2
            # --auto-servernum picks a free :N display.
            # -screen 0 1280x800x24 matches the size our anti-detection
            # JS expects (window.outerWidth/Height shim defaults).
            exec xvfb-run --auto-servernum --server-args="-screen 0 1280x800x24" \
                env BENCH_HEADFUL=1 "$BIN" "${ARGS[@]}"
        else
            echo "[headful] xvfb-run not found AND no DISPLAY; install xvfb or run with a real display" >&2
            echo "  ubuntu: sudo apt install xvfb" >&2
            exit 3
        fi
        ;;
    Darwin|MINGW*|MSYS*|CYGWIN*)
        # macOS Quartz / Windows Win32: real display always present.
        echo "[headful] $(uname -s): native display, no wrapping needed" >&2
        exec env BENCH_HEADFUL=1 "$BIN" "${ARGS[@]}"
        ;;
    *)
        echo "[headful] unknown OS $(uname -s); attempting direct invocation" >&2
        exec env BENCH_HEADFUL=1 "$BIN" "${ARGS[@]}"
        ;;
esac
