#!/bin/bash
set -e

# tmpdir for everything
TMPDIR="$(mktemp -d)"
cd "$TMPDIR"
WWW="$TMPDIR/www"
mkdir -p "$WWW"

PORT=$(( ( RANDOM % 20000 ) + 20000 ))

cat > "$WWW/index.html" <<'EOF'
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>BusyBox Test Page</title>
</head>
<body>
  <h1>Hello from BusyBox httpd</h1>
  <p>This page is served locally for Playwright testing.</p>
</body>
</html>
EOF

systemd-run --scope --unit busybox-httpd \
    busybox httpd -f -p "$PORT" -h "$WWW" &


cleanup() {
  systemctl stop busybox-httpd.scope || true
  rm -rf "$TMPDIR"
}
trap cleanup EXIT INT TERM

# basic test
playwright --version


# wlheadless-run automatically:
# - creates a Wayland socket
# - sets WAYLAND_DISPLAY
# - runs cage headless
# - cleans up on exit

tee test.js <<'EOF'
#!/usr/bin/node
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({
    executablePath: "/usr/bin/chromium",
    args: [
      "--ozone-platform=wayland",
      "--enable-features=UseOzonePlatform",
      "--use-gl=egl",
      "--no-sandbox",
      "--headless=old"
    ],
  });

  const page = await browser.newPage();
  await page.goto("http://localhost:"+process.argv[2]);
  console.log("H1:", await page.textContent("h1"));

  await browser.close();
})();
EOF
chmod +x test.js

wlheadless-run -c cage -- ./test.js "$PORT"
