#!/usr/bin/env bash
set -euo pipefail
# Load the T3 Connect test-stage environment before running this script.
# Run from the checkout to test; use a fresh PROOF_FIXTURES_DIR each run.
: "${PROOF_FIXTURES_DIR:?Choose a fresh scratch directory}"
mkdir -p "$PROOF_FIXTURES_DIR/bin" "$PROOF_FIXTURES_DIR/primary-bin" "$PROOF_FIXTURES_DIR/review-repo" .t3/healthy-repo
printf '#!/bin/sh\necho "Review server"\n' > "$PROOF_FIXTURES_DIR/bin/hostnamectl"
printf '#!/bin/sh\necho "Workstation"\n' > "$PROOF_FIXTURES_DIR/primary-bin/hostnamectl"
chmod +x "$PROOF_FIXTURES_DIR/bin/hostnamectl" "$PROOF_FIXTURES_DIR/primary-bin/hostnamectl"
seed_repo() {
  git -C "$1" init -q --initial-branch=main
  printf 'Synthetic project\n' > "$1/README.md"
  git -C "$1" add README.md
  git -C "$1" -c user.name=Scenario -c user.email=scenario@example.invalid commit -qm 'Initial commit'
  git -C "$1" remote add origin "$2"
}
seed_repo "$PROOF_FIXTURES_DIR/review-repo" https://github.com/scenario/review.git
seed_repo "$PWD/.t3/healthy-repo" https://github.com/scenario/healthy.git
node apps/server/src/bin.ts connect login --headless --base-dir "$PROOF_FIXTURES_DIR/connect-home"
node apps/server/src/bin.ts connect link --headless --base-dir "$PROOF_FIXTURES_DIR/connect-home"
node apps/server/src/bin.ts project add "$PROOF_FIXTURES_DIR/review-repo" --title 'Review repository' --base-dir "$PROOF_FIXTURES_DIR/connect-home"
node apps/server/src/bin.ts project add "$PWD/.t3/healthy-repo" --title 'Healthy repository' --base-dir "$PWD/.t3"
# In separate tracked foreground shell sessions, with stage variables loaded:
# export T3CODE_DEV_SEED=0 GH_TOKEN=scenario-fixture
# export NODE_OPTIONS="--import=$PROOF_FIXTURES_DIR/forge-fixture.mjs"
# export FIXTURE_LOG="$PROOF_FIXTURES_DIR/forge.log"
# PATH="$PROOF_FIXTURES_DIR/bin:$PATH" node apps/server/src/bin.ts serve --base-dir "$PROOF_FIXTURES_DIR/connect-home" --port 32905 --host 127.0.0.1
# PATH="$PROOF_FIXTURES_DIR/primary-bin:$PATH" vp run dev --no-seed
# Remove the automatically bootstrapped server project if present:
# node apps/server/src/bin.ts project remove "$PWD/apps/server" --force --base-dir "$PWD/.t3"
# After capture, stop the tracked server sessions and run:
# node apps/server/src/bin.ts connect logout --base-dir "$PROOF_FIXTURES_DIR/connect-home"
