#!/bin/bash
# Run the web-content POC against an ASAN chrome build.
#
# Usage: ./run.sh [chrome-binary] [iterations]
#
# Each iteration uses a fresh user-data-dir so the
# FileSystemAccessBucketPathWatcher::Initialize() write fires once per run.
# Under ThreadSanitizer this reports a data race deterministically.

set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
CHROME="${1:-out/asan/chrome}"
N="${2:-1}"
PORT=8765

# Start the POC server.
pkill -f "server.py $PORT" 2>/dev/null || true
python3 "$HERE/server.py" "$PORT" >/dev/null 2>&1 &
SRV=$!
trap "kill $SRV 2>/dev/null" EXIT
sleep 1

for i in $(seq 1 "$N"); do
  PROFILE="/tmp/chrome-poc-profile-$$-$i"
  rm -rf "$PROFILE"
  ASAN_OPTIONS="detect_odr_violation=0:symbolize=1:abort_on_error=1" \
  timeout 15 "$CHROME" \
    --headless=new \
    --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
    --disable-gpu --no-sandbox \
    --enable-logging=stderr \
    --user-data-dir="$PROFILE" \
    "http://127.0.0.1:$PORT/poc.html" 2>&1 \
  | grep -E "AddressSanitizer|SUMMARY|ERROR.*Sanitizer|SEGV|heap-|CONSOLE.*\[\*\]|FATAL"
  rm -rf "$PROFILE"
  echo "--- run $i done ---"
done
