#!/usr/bin/env bash
set -euo pipefail
# Usage: bash seed-and-run.sh <checkout> <new-state-directory> <web-port>
checkout=$(realpath "$1")
state=$(realpath -m "$2")
port=$3
fixture=$(realpath "$(dirname "$0")/github-permission-fixture.mjs")
mkdir -p "$state/repository"
git -C "$state/repository" init -q --initial-branch=main
git -C "$state/repository" remote add origin https://github.com/scenario/check-access.git
git -C "$state/repository" -c user.name=Scenario -c user.email=scenario@example.invalid commit -q --allow-empty -m 'Initial commit'
cd "$checkout"
T3CODE_DEV_SEED=0 GH_TOKEN=scenario-placeholder NODE_OPTIONS="--import=$fixture" \
 node scripts/scenarios/start-app.ts web "$state/home" 127.0.0.1 "$port" > "$state/app.log" 2>&1 &
app_pid=$!
trap 'kill -INT "$app_pid"; wait "$app_pid" || true' EXIT
# Wait for the server-created pairing file, then register through the real app CLI.
for attempt in $(seq 1 120); do
 if test -f "$state/home/pairing-path"; then break; fi
 sleep 1
done
node apps/server/src/bin.ts project add "$state/repository" --title 'Check access demo' --base-dir "$state/home"
printf 'Open the pairing path from %s/home/pairing-path at http://127.0.0.1:%s, then follow reproduction.md.\n' "$state" "$port"
wait "$app_pid"
