#!/usr/bin/env bash
# Regression tests for od-worktree's checkout registration — the pointer shim-drift-check
# follows from the deploy clone to the checkouts that hold worktrees. Runs with a PATH of
# real system binaries only, so it never spawns a PATH shim.
set -uo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
ODWT="$ROOT/bin/od-worktree"
PASS=0; FAIL=0
ok()  { PASS=$((PASS+1)); printf 'PASS %s\n' "$1"; }
bad() { FAIL=$((FAIL+1)); printf 'FAIL %s\n     %s\n' "$1" "$2"; }

TMP=$(mktemp -d "${TMPDIR:-/tmp}/odwt-reg-XXXX")
trap 'rm -rf "$TMP"' EXIT

REPO="$TMP/repo"
mkdir -p "$REPO"
export PATH=/usr/bin:/bin
git -C "$REPO" init -q
git -C "$REPO" config user.email t@t; git -C "$REPO" config user.name t; git -C "$REPO" config commit.gpgsign false
: >"$REPO/f"; git -C "$REPO" add -A; git -C "$REPO" commit -qm init

REG="$TMP/state/shim-repos"
run() { (cd "$1" && OD_SHIM_REPOS_FILE="$REG" bash "$ODWT" list) >"$TMP/out" 2>"$TMP/err"; }

run "$REPO"
rc=$?
[[ $rc -eq 0 && "$(cat "$REG" 2>/dev/null)" == "$REPO" ]] \
  && ok "the checkout is registered on first use" \
  || bad "the checkout is registered on first use" "rc=$rc reg=$(cat "$REG" 2>/dev/null) err=$(cat "$TMP/err")"

run "$REPO"; run "$REPO"
[[ "$(wc -l <"$REG")" -eq 1 ]] \
  && ok "repeated use does not duplicate the entry" \
  || bad "repeated use does not duplicate the entry" "reg=$(cat "$REG")"

printf '%s\n' "$TMP/elsewhere" >"$REG"
run "$REPO"
[[ "$(cat "$REG")" == "$TMP/elsewhere
$REPO" ]] \
  && ok "an existing registry is appended to, never replaced" \
  || bad "an existing registry is appended to, never replaced" "reg=$(cat "$REG")"

WT="$REPO/.worktrees/slug"
(cd "$REPO" && OD_SHIM_REPOS_FILE="$REG" bash "$ODWT" add slug HEAD) >/dev/null 2>&1
rm -f "$REG"
(cd "$WT" && OD_SHIM_REPOS_FILE="$REG" bash "$ODWT" list) >/dev/null 2>"$TMP/err"
[[ "$(cat "$REG" 2>/dev/null)" == "$REPO" ]] \
  && ok "use from inside a worktree registers the main checkout" \
  || bad "use from inside a worktree registers the main checkout" "reg=$(cat "$REG" 2>/dev/null) err=$(cat "$TMP/err")"

rm -rf "$TMP/state"
: >"$TMP/state"
run "$REPO"
rc=$?
[[ $rc -eq 0 && "$(cat "$TMP/err")" == *"cannot record"* ]] \
  && ok "an unwritable registry warns and still serves the worktree command" \
  || bad "an unwritable registry warns and still serves the worktree command" "rc=$rc err=$(cat "$TMP/err")"

echo
echo "PASS=$PASS FAIL=$FAIL"
[[ "$FAIL" -eq 0 ]]
