#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
CHROMIUM="${CHROMIUM:-$(command -v chromium || command -v chromium-browser || command -v google-chrome || command -v google-chrome-stable || true)}"

if [[ -z "$CHROMIUM" ]]; then
  echo "missing Chromium-compatible browser; set CHROMIUM=/path/to/browser" >&2
  exit 1
fi

if [[ "${SKIP_INI_BUILD:-0}" != "1" ]]; then
  "$ROOT_DIR/tools/build_ini_panel.sh"
fi
if [[ "${SKIP_INTERP_BUILD:-0}" != "1" ]]; then
  "$ROOT_DIR/tools/build_wasm_core.sh"
fi

TMP_DIR="$(mktemp -d)"
PORT_FILE="$TMP_DIR/port"
SERVER_LOG="$TMP_DIR/server.log"
CHROME_PROFILE="$TMP_DIR/chrome-profile"
mkdir -p "$CHROME_PROFILE"

cleanup() {
  if [[ -n "${SERVER_PID:-}" ]]; then
    kill "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
  fi
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

python3 - <<'PY' "$ROOT_DIR" "$PORT_FILE" >"$SERVER_LOG" 2>&1 &
import functools
import http.server
import pathlib
import socketserver
import sys

root = pathlib.Path(sys.argv[1])
port_file = pathlib.Path(sys.argv[2])

handler = functools.partial(http.server.SimpleHTTPRequestHandler, directory=str(root))
with socketserver.TCPServer(("127.0.0.1", 0), handler) as httpd:
    port_file.write_text(str(httpd.server_address[1]), encoding="ascii")
    httpd.serve_forever()
PY
SERVER_PID=$!

for _ in $(seq 1 100); do
  [[ -s "$PORT_FILE" ]] && break
  sleep 0.05
done

if [[ ! -s "$PORT_FILE" ]]; then
  echo "browser smoke HTTP server did not start" >&2
  cat "$SERVER_LOG" >&2 || true
  exit 1
fi

PORT="$(cat "$PORT_FILE")"
URL="http://127.0.0.1:$PORT/tests/browser/ini_panel_smoke.html"
OUT="$TMP_DIR/chromium.out"

"$CHROMIUM" \
  --headless=new \
  --disable-gpu \
  --no-sandbox \
  --user-data-dir="$CHROME_PROFILE" \
  --virtual-time-budget=10000 \
  --dump-dom \
  "$URL" >"$OUT" 2>&1

if ! grep -Fq "browser_ini_opfs_smoke=ok" "$OUT"; then
  echo "browser INI/OPFS smoke failed" >&2
  sed -n '1,220p' "$OUT" >&2
  exit 1
fi

echo "browser_ini_opfs_smoke=ok"
