#!/usr/bin/env bash
# Local test of deploy/release.sh on a fake box tree, with php, composer, sudo, install, chown, systemctl, supervisorctl,
# curl, pgrep stubbed. Run on Linux (WSL): bash deploy/test/stub-run.sh. Touches only a temporary folder.
# Scenarios: cutover from the old tree; a normal deploy; a failed probe rolls back; a ONE_WAY migration stops; a wrong
# sum stops; the prune keeps KEEP releases.
set -euo pipefail
KIT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
W=$(mktemp -d /tmp/fleet-release-test.XXXXXX)
trap 'rm -rf "$W"' EXIT
B=$W/bin; mkdir -p "$B"
pass=0; fail=0
ok() { echo "  ok: $1"; pass=$((pass + 1)); }
ko() { echo "  FAIL: $1"; fail=$((fail + 1)); }

# --- stubs
cat > "$B/sudo" <<'S'
#!/usr/bin/env bash
while [ $# -gt 0 ]; do case "$1" in -u|-g) shift 2 ;; -H|-E|-n) shift ;; *) break ;; esac; done
exec "$@"
S
cat > "$B/install" <<'S'
#!/usr/bin/env bash
a=(); while [ $# -gt 0 ]; do case "$1" in -o|-g) shift 2 ;; *) a+=("$1"); shift ;; esac; done
exec /usr/bin/install "${a[@]}"
S
printf '#!/usr/bin/env bash\nexit 0\n' > "$B/chown"; cp "$B/chown" "$B/chgrp"
printf '#!/usr/bin/env bash\necho "systemctl $*" >> "$STUB_LOG"\n' > "$B/systemctl"
printf '#!/usr/bin/env bash\necho "supervisorctl $*" >> "$STUB_LOG"\n[ "$1" = status ] && echo "reverb RUNNING" || true\n' > "$B/supervisorctl"
printf '#!/usr/bin/env bash\nexit 1\n' > "$B/pgrep"
printf '#!/usr/bin/env bash\ncat "$STUB_HTTP"\n' > "$B/curl"
cat > "$B/composer" <<'S'
#!/usr/bin/env bash
mkdir -p vendor/composer && echo '<?php // autoload' > vendor/autoload.php && echo "composer $*" >> "$STUB_LOG"
S
cat > "$B/php" <<'S'
#!/usr/bin/env bash
[ "$1" = artisan ] || exit 1
echo "php artisan $2 (in $(pwd -P))" >> "$STUB_LOG"
case "$2" in
  --version) echo "Laravel Framework 10.50.2" ;;
  route:list) echo '[{"uri":"a"},{"uri":"b"},{"uri":"c"}]' ;;
  migrate:status) [ -f "$STUB_PENDING.down" ] && { echo "SQLSTATE[HY000] [2002] Connection refused" >&2; exit 1; }
                  cat "$STUB_PENDING" 2>/dev/null || true; echo "  2026_01_01_000000_base ...... Ran" ;;
  migrate) : > "$STUB_PENDING" ;;
  *) echo "ok $2" ;;
esac
S
chmod +x "$B"/*
export PATH="$B:$PATH" STUB_LOG=$W/stub.log STUB_HTTP=$W/http STUB_PENDING=$W/pending PYTHON=python3
echo 401 > "$W/http"

# --- a fake box: the old tree with its storage link and .env
WWW=$W/www; mkdir -p "$WWW/storage/logs" "$WWW/storage/app/public" "$WWW/storage/framework"
APP=$WWW/app
mkdir -p "$APP/.git" "$APP/bootstrap/cache" "$APP/public" "$APP/vendor" "$APP/database/migrations"
ln -s "$WWW/storage" "$APP/storage"
echo "APP_KEY=secret" > "$APP/.env"
echo '{"lock":1}' > "$APP/composer.lock"; echo '<?php' > "$APP/vendor/autoload.php"; touch "$APP/artisan"
# archives: one per fake commit
mk() { # $1 sha, $2 lock content, $3 optional migration file name, $4 its content
    local s=$W/src-$1; mkdir -p "$s/bootstrap/cache" "$s/public" "$s/storage/logs" "$s/database/migrations"
    touch "$s/artisan" "$s/bootstrap/app.php" "$s/storage/logs/.gitignore" "$s/bootstrap/cache/.gitignore"
    echo "$2" > "$s/composer.lock"
    [ -n "${3:-}" ] && echo "${4:-}" > "$s/database/migrations/$3.php"
    tar -czf "$W/fleet-$1.tgz" -C "$s" .
    sha256sum "$W/fleet-$1.tgz" | cut -d' ' -f1
}
settings() {
    printf 'APP=%s\nBASE=%s\nSTORAGE=%s\nOWNER=me\nPHP=php\nFPM=php8.2-fpm\nQRESTART_USER=me\nREVERB=reverb\n' "$APP" "$WWW/fleet" "$WWW/storage"
    printf 'URL=http://box\nPROBES="/p1 /p2"\nEXPECT=401\nDUMP=no\nKEEP=3\nENV_MODE=640\nSLEEP_PROBE=0\nSLEEP_ERRORS=0\n'
    printf 'COMPOSER=%s\n' "${TEST_COMPOSER:-composer}"
}
run() { # $1 sha, $2 sum, $3 cutover
    { settings; printf 'SHA=%s\nSUM=%s\nTARGET=test\nCUTOVER=%s\nRELOAD=%s\nDEPLOYER=test\nTGZ=%s\n' "$1" "$2" "$3" "${TEST_RELOAD:-yes}" "$W/fleet-$1.tgz"; cat "$KIT/release.sh"; } > "$W/run.sh"
    bash "$W/run.sh" > "$W/out.txt" 2>&1
}
live() { readlink -e "$APP"; }

echo "== 1. cutover from the old tree"
S1=0123456789abcdef0123456789abcdef01234567
U1=$(mk $S1 '{"lock":1}')
if run $S1 "$U1" yes; then ok "cutover ran"; else ko "cutover failed"; tail -20 "$W/out.txt"; fi
[ "$(live)" = "$WWW/fleet/releases/$S1" ] && ok "app links to the new release" || ko "app is $(live)"
ls -d "$WWW"/fleet/releases/legacy-* >/dev/null 2>&1 && ok "legacy folder kept" || ko "no legacy folder"
[ -f "$WWW/fleet/shared/.env" ] && grep -q secret "$WWW/fleet/shared/.env" && ok "shared .env copied" || ko "shared .env missing"
[ "$(readlink "$WWW/fleet/releases/$S1/.env")" = "$WWW/fleet/shared/.env" ] && ok ".env linked" || ko ".env not linked"
[ "$(readlink "$WWW/fleet/releases/$S1/storage")" = "$WWW/storage" ] && ok "storage linked" || ko "storage not linked"
grep -q 'copied from the live release' "$W/out.txt" && ok "vendor copied (same lock)" || ko "vendor not copied"
grep -q 'systemctl reload php8.2-fpm' "$W/stub.log" && grep -q 'supervisorctl restart reverb' "$W/stub.log" && ok "fpm reloaded, reverb restarted" || ko "no reload / restart"

echo "== 2. a normal deploy, new lock"
S2=1123456789abcdef0123456789abcdef01234567
U2=$(mk $S2 '{"lock":2}')
if run $S2 "$U2" no; then ok "deploy ran"; else ko "deploy failed"; tail -20 "$W/out.txt"; fi
[ "$(live)" = "$WWW/fleet/releases/$S2" ] && ok "app links to $S2" || ko "app is $(live)"
grep -q 'composer.lock changed: full install' "$W/out.txt" && ok "full install on a new lock" || ko "lock change not seen"
[ "$(wc -l < "$WWW/fleet/deploys.log")" = 2 ] && ok "deploys.log has 2 lines" || ko "deploys.log: $(cat "$WWW/fleet/deploys.log")"

echo "== 3. a failed probe rolls back"
S3=2123456789abcdef0123456789abcdef01234567
U3=$(mk $S3 '{"lock":2}')
cat > "$B/curl" <<'S'
#!/usr/bin/env bash
# 401 until the switch, 500 from the new release, 401 again once rolled back
n=$(cat "$STUB_HTTP.n" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > "$STUB_HTTP.n"
if [ "$n" -gt 2 ] && [ "$n" -le 4 ]; then echo 500; else echo 401; fi
S
chmod +x "$B/curl"; rm -f "$W/http.n"
if run $S3 "$U3" no; then ko "the deploy should have stopped"; else ok "the deploy stopped"; fi
[ "$(live)" = "$WWW/fleet/releases/$S2" ] && ok "back on $S2" || ko "app is $(live)"
grep -q 'ROLLED BACK' "$WWW/fleet/deploys.log" && ok "rollback recorded" || ko "rollback not recorded"
printf '#!/usr/bin/env bash\ncat "$STUB_HTTP"\n' > "$B/curl"; chmod +x "$B/curl"

echo "== 4. a ONE_WAY migration stops before anything changes"
S4=3123456789abcdef0123456789abcdef01234567
U4=$(mk $S4 '{"lock":2}' 2026_10_30_000001_drop_x '<?php // ONE_WAY: drops a column the live code reads')
echo "  2026_10_30_000001_drop_x ...... Pending" > "$W/pending"
if run $S4 "$U4" no; then ko "should have stopped"; else ok "stopped"; fi
grep -q 'marked ONE_WAY' "$W/out.txt" && ok "ONE_WAY named" || ko "reason: $(grep STOP "$W/out.txt")"
[ "$(live)" = "$WWW/fleet/releases/$S2" ] && ok "live unchanged" || ko "app is $(live)"
: > "$W/pending"

echo "== 5. a wrong sum stops"
S5=4123456789abcdef0123456789abcdef01234567
mk $S5 '{"lock":2}' >/dev/null
if run $S5 "$(printf '%064d' 0)" no; then ko "should have stopped"; else ok "stopped"; fi
grep -q "sum differs" "$W/out.txt" && ok "sum named" || ko "reason: $(grep STOP "$W/out.txt")"

echo "== 6. an additive migration runs, then the prune keeps 3"
S6=5123456789abcdef0123456789abcdef01234567
U6=$(mk $S6 '{"lock":2}' 2026_10_30_000002_add_y '<?php // adds a table')
echo "  2026_10_30_000002_add_y ...... Pending" > "$W/pending"
run $S6 "$U6" no && ok "deploy with a migration ran" || { ko "failed"; tail -20 "$W/out.txt"; }
grep -q 'php artisan down' "$W/stub.log" && grep -q 'php artisan migrate ' "$W/stub.log" && grep -q 'php artisan up' "$W/stub.log" \
    && ok "maintenance, migrate, up" || ko "migration path"
for n in 6 7 8; do S=${n}123456789abcdef0123456789abcdef01234567; U=$(mk "$S" '{"lock":2}'); run "$S" "$U" no || ko "deploy $S"; sleep 1; done
N=$(ls -1d "$WWW"/fleet/releases/*/ | grep -c -E '/[0-9a-f]{40}/$')
[ "$N" -le 4 ] && ok "$N commit releases left (3 kept + the previous one at most)" || ko "$N releases left"
ls -d "$WWW"/fleet/releases/legacy-* >/dev/null 2>&1 && ok "legacy never pruned" || ko "legacy pruned"

echo "== 7. a database that does not answer stops before the switch"
S9=9123456789abcdef0123456789abcdef01234567
U9=$(mk $S9 '{"lock":2}')
BEFORE=$(live)
touch "$W/pending.down"
if run $S9 "$U9" no; then ko "should have stopped"; else ok "stopped"; fi
grep -q "cannot read the migrations' state" "$W/out.txt" && ok "reason named" || ko "reason: $(grep STOP "$W/out.txt")"
[ "$(live)" = "$BEFORE" ] && ok "live unchanged" || ko "app is $(live)"
rm -f "$W/pending.down"

echo "== 8. cutover of a tree that keeps storage inside it (as the UAT dev trees)"
WWW=$W/www2; APP=$WWW/app
mkdir -p "$APP/.git" "$APP/bootstrap/cache" "$APP/public" "$APP/vendor" "$APP/storage/logs" "$APP/storage/app/public"
echo "APP_KEY=x" > "$APP/.env"; echo '{"lock":1}' > "$APP/composer.lock"; echo '<?php' > "$APP/vendor/autoload.php"
touch "$APP/artisan" "$APP/storage/logs/old.log"
S10=a123456789abcdef0123456789abcdef01234567
U10=$(mk $S10 '{"lock":1}')
if run $S10 "$U10" yes; then ok "cutover ran"; else ko "cutover failed"; tail -20 "$W/out.txt"; fi
[ -d "$WWW/storage" ] && [ ! -L "$WWW/storage" ] && [ -f "$WWW/storage/logs/old.log" ] && ok "storage moved out with its files" || ko "storage not moved"
[ "$(readlink -e "$(live)/storage")" = "$WWW/storage" ] && ok "the release's storage is the moved folder" || ko "release storage: $(readlink -e "$(live)/storage")"
L=$(ls -d "$WWW"/fleet/releases/legacy-* | head -1)
[ "$(readlink "$L/storage")" = "$WWW/storage" ] && ok "the legacy folder's storage is linked back" || ko "legacy storage: $(readlink "$L/storage")"

echo "== 9. no composer on the box"
TEST_COMPOSER=no-composer-here
S11=b123456789abcdef0123456789abcdef01234567
U11=$(mk $S11 '{"lock":1}')
if run $S11 "$U11" no; then ok "same lock: deployed without composer"; else ko "failed"; tail -15 "$W/out.txt"; fi
grep -q 'the copied vendor is used as it is' "$W/out.txt" && ok "said so" || ko "no note"
BEFORE=$(live)
S12=c123456789abcdef0123456789abcdef01234567
U12=$(mk $S12 '{"lock":9}')
if run $S12 "$U12" no; then ko "should have stopped"; else ok "changed lock: stopped"; fi
[ "$(live)" = "$BEFORE" ] && ok "live unchanged" || ko "app is $(live)"
unset TEST_COMPOSER

echo "== 10. a probe that answers 404 before and after does not roll back"
cat > "$B/curl" <<'S'
#!/usr/bin/env bash
for a in "$@"; do u=$a; done
case "$u" in *p2) echo 404 ;; *) echo 401 ;; esac
S
chmod +x "$B/curl"
S13=d123456789abcdef0123456789abcdef01234567
U13=$(mk $S13 '{"lock":1}')
if run $S13 "$U13" no; then ok "deployed"; else ko "rolled back"; tail -12 "$W/out.txt"; fi
grep -q '/p2 -> 404 (as before the deploy)' "$W/out.txt" && ok "the 404 seen as before" || ko "no note"
[ "$(live)" = "$WWW/fleet/releases/$S13" ] && ok "live is the new release" || ko "app is $(live)"
printf '#!/usr/bin/env bash
cat "$STUB_HTTP"
' > "$B/curl"; chmod +x "$B/curl"

echo "== 11. RELOAD=no switches the link and leaves php-fpm and reverb alone"
TEST_RELOAD=no
S14=e123456789abcdef0123456789abcdef01234567
U14=$(mk $S14 '{"lock":1}')
: > "$STUB_LOG"
if run $S14 "$U14" no; then ok "deployed"; else ko "failed"; tail -12 "$W/out.txt"; fi
[ "$(live)" = "$WWW/fleet/releases/$S14" ] && ok "live is the new release" || ko "app is $(live)"
grep -q 'systemctl reload' "$STUB_LOG" && ko "php-fpm reloaded" || ok "php-fpm not reloaded"
grep -q 'supervisorctl restart' "$STUB_LOG" && ko "reverb restarted" || ok "reverb not restarted"
grep -q 'php artisan queue:restart' "$STUB_LOG" && ok "queue workers restarted" || ko "no queue:restart"
tail -1 "$WWW/fleet/deploys.log" | grep -q 'ok (no php-fpm reload)' && ok "recorded without reload" || ko "deploys.log: $(tail -1 "$WWW/fleet/deploys.log")"
grep -q 'way back: .*queue:restart' "$W/out.txt" && ! grep -q 'way back: .*systemctl' "$W/out.txt" && ok "way back without reload" || ko "way back line"
unset TEST_RELOAD

echo
echo "passed $pass, failed $fail"
[ "$fail" = 0 ]
