#!/usr/bin/env bash
# Supply two clean checkouts at the SHAs below and a new scratch directory.
# Usage: bash reproduce.sh HEAD_CHECKOUT BASE_CHECKOUT SCRATCH
set -euo pipefail
head_checkout=$1
base_checkout=$2
scratch=$3
mkdir -p "$scratch/sample"
for checkout in "$head_checkout" "$base_checkout"; do
  (cd "$checkout"; vp i; cd apps/web; vp build)
done
cp "$head_checkout/apps/web/test/fixtures/images/photo.heic" "$scratch/sample/photo.heic"
git init --quiet --initial-branch=main "$scratch/sample"
git -C "$scratch/sample" add photo.heic
git -C "$scratch/sample" -c user.name=Proof -c user.email=proof@example.invalid commit -qm 'HEIC fixture'
(cd "$head_checkout"; exec env T3CODE_DEV_SEED=0 node apps/server/src/bin.ts serve --host 127.0.0.1 --port 18498 --base-dir "$scratch/head-state") > "$scratch/head-server.log" 2>&1 &
head_pid=$!
(cd "$base_checkout"; exec env T3CODE_DEV_SEED=0 node apps/server/src/bin.ts serve --host 127.0.0.1 --port 18499 --base-dir "$scratch/base-state") > "$scratch/base-server.log" 2>&1 &
base_pid=$!
trap 'kill "$head_pid" "$base_pid" 2>/dev/null || true' EXIT
# Wait for real HTTP readiness, without exposing pairing credentials from logs.
node -e 'Promise.all(process.argv.slice(1).map(async u=>{for(let i=0;i<120;i++){try{if((await fetch(u)).ok)return}catch{}await new Promise(r=>setTimeout(r,500))}throw Error("Server did not start")}))' http://127.0.0.1:18498/.well-known/t3/environment http://127.0.0.1:18499/.well-known/t3/environment
(cd "$head_checkout"; node apps/server/src/bin.ts project add --base-dir "$scratch/head-state" --title 'HEIC proof' "$scratch/sample")
(cd "$base_checkout"; node apps/server/src/bin.ts project add --base-dir "$scratch/base-state" --title 'HEIC proof' "$scratch/sample")
driver_dir=$(cd "$(dirname "$0")"; pwd)
for index in 0 1 2 3 4 5 6; do
  node "$driver_dir/measure.mjs" "$head_checkout" "$base_checkout" "$scratch" 1 "$index"
done
# Pass the seven run directories in creation order to summarize.mjs.
