#!/bin/bash
# Runner for the PressureRecord.toJSON() ownContributionEstimate leak POC.
#
# This launches Chrome against poc.html, then forces X input focus onto the
# Chrome window. The Compute Pressure API only delivers samples while the tab
# has implicit focus (RenderWidgetHostImpl::is_focused()); under Xvfb without a
# window manager, no window is focused by default, so we set it explicitly.
# This mirrors what happens on a real desktop where the user's tab is focused.

set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME=${CHROME:-/chromium/chromium/src/out/asan/chrome}
PROFILE=/tmp/chrome-poc-profile
PORT=8090

rm -rf "$PROFILE"

# Start the POC server if not already running.
if ! curl -s -o /dev/null "http://127.0.0.1:${PORT}/poc.html"; then
  ( cd "$HERE" && python3 server.py & )
  sleep 1
fi

"$CHROME" \
  --no-sandbox --disable-gpu \
  --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
  --disable-component-update --disable-background-networking \
  --enable-logging=stderr --v=0 \
  --user-data-dir="$PROFILE" \
  "http://127.0.0.1:${PORT}/poc.html" 2>&1 &
CHROME_PID=$!

# Give Chrome time to create its window, then force X focus onto it (and keep
# re-asserting focus). On a real desktop the user's tab is focused; under
# automation we have to do it explicitly so HasImplicitFocus() passes.
for i in $(seq 1 20); do
  sleep 2
  python3 "$HERE/xfocus.py" "PressureRecord" 2>&1 || \
    python3 "$HERE/xfocus.py" "POC-DONE" 2>&1 || \
    python3 "$HERE/xfocus.py" "Chromium" 2>&1 || true
  if ! kill -0 "$CHROME_PID" 2>/dev/null; then break; fi
done

kill "$CHROME_PID" 2>/dev/null
wait "$CHROME_PID" 2>/dev/null
