#!/bin/bash
# Reproduce the Ganesh-Vk renderArea-scoped stencil-clear / attachment-global
# fHasPerformedInitialClear granularity mismatch.
#
# 1. Apply the instrumentation patch (observability only — does not change
#    behaviour) to Skia inside the Chromium tree.
# 2. Build chrome.
# 3. Serve poc.html and load it in headless Chrome with the Ganesh-Vulkan
#    raster backend (SwiftShader Vulkan ICD on hosts without a GPU).
#
# Usage:  CHROMIUM_SRC=/path/to/chromium/src ./run.sh
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
: "${CHROMIUM_SRC:=/chromium/chromium/src}"
: "${OUTDIR:=out/asan}"
: "${PORT:=19283}"

echo "[*] Applying instrumentation patch (observability only)"
( cd "$CHROMIUM_SRC/third_party/skia" && git apply --check "$HERE/chromium-changes.patch" 2>/dev/null && git apply "$HERE/chromium-changes.patch" ) || \
  echo "    (already applied or apply failed — continuing)"

echo "[*] Building chrome"
( cd "$CHROMIUM_SRC" && autoninja -C "$OUTDIR" chrome )

echo "[*] Starting POC HTTP server on :$PORT"
( cd "$HERE" && python3 server.py "$PORT" ) &
SRV=$!
trap "kill $SRV 2>/dev/null; ( cd '$CHROMIUM_SRC/third_party/skia' && git checkout -- src/gpu/ganesh/ops/OpsTask.cpp )" EXIT
sleep 1

echo "[*] Launching Chrome (Ganesh-Vulkan / SwiftShader)"
rm -rf /tmp/chrome-poc-profile
cd "$CHROMIUM_SRC/$OUTDIR"
VK_ICD_FILENAMES="$PWD/vk_swiftshader_icd.json" timeout 25 ./chrome \
  --headless=new --no-sandbox --no-first-run --no-default-browser-check \
  --ignore-gpu-blocklist --disable-gpu-sandbox \
  --enable-features=Vulkan --use-vulkan=swiftshader \
  --disable-skia-graphite \
  --enable-gpu-rasterization --enable-accelerated-2d-canvas \
  --disable-vulkan-fallback-to-gl-for-testing \
  --use-gl=angle --use-angle=swiftshader \
  --enable-logging=stderr \
  --user-data-dir=/tmp/chrome-poc-profile \
  "http://127.0.0.1:$PORT/poc.html" 2>&1 \
  | grep -E "STENCIL-POC.*512x512|PARTIAL initial|BUG TRIGGERED|stencilLoadOp=kLoad \(fallthrough|CONSOLE|\*{8}"

echo
echo "[*] Look for '******** BUG TRIGGERED ********' above."
echo "    On a real (non-zeroing) Vulkan driver, drop --use-vulkan=swiftshader"
echo "    and the VK_ICD_FILENAMES env; the leaked stencil bytes then become"
echo "    visible in Canvas B's getImageData() output."
