#!/usr/bin/env bash
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCRIPT="$ROOT/packaging/stage-backend-release.sh"
RELEASE_TOOL="$ROOT/packaging/backend-release.sh"
TESTROOT="${XDG_CACHE_HOME:-$HOME/.cache}/overdeck/tests/backend-stage/run-$$-$RANDOM"
BACKEND="$TESTROOT/backend"
BIN="$TESTROOT/bin"
LOG="$TESTROOT/runtime.log"
mkdir -p "$BIN"
trap 'chmod -R u+w "$TESTROOT" 2>/dev/null; rm -rf "$TESTROOT"' EXIT

fails=0
check() {
  if (( $1 == 0 )); then printf 'ok - %s\n' "$2"
  else printf 'FAIL - %s\n' "$2"; fails=$((fails + 1)); fi
}

ORIGINAL_PATH=$PATH
cat >"$BIN/pnpm" <<'SH'
#!/usr/bin/env bash
printf '%s\n' "${LOCAL_GATE_ACTIVE-}" >"$PNPM_ENV_LOG"
PATH="$ORIGINAL_PATH" exec pnpm "$@"
SH
chmod +x "$BIN/pnpm"

SHA=$(git -C "$ROOT" rev-parse HEAD)
release=$(LOCAL_GATE_ACTIVE= PATH="$BIN:$PATH" ORIGINAL_PATH="$ORIGINAL_PATH" PNPM_ENV_LOG="$TESTROOT/pnpm-env.log" \
  OVERDECK_DEPLOY_DIR="$ROOT" OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" \
  OVERDECK_BACKEND_RELEASE_TOOL="$RELEASE_TOOL" bash "$SCRIPT" collector "$SHA")
if [[ "$release" == "$BACKEND/collector/releases/$SHA" ]] \
  && OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" bash "$RELEASE_TOOL" validate collector "$SHA" \
  && [[ -x "$release/bin/start" ]] \
  && [[ ! -w "$release/collector/src/index.ts" ]]; then rc=0; else rc=1; fi
check "$rc" 'an exact Git revision becomes a valid immutable collector artifact'

if [[ "$(<"$TESTROOT/pnpm-env.log")" == 1 ]]; then rc=0; else rc=1; fi
check "$rc" 'dependency snapshot materializes in the activation host state tree'

if [[ -z "$(find "$release" -type f -links +1 -print -quit)" ]]; then rc=0; else rc=1; fi
check "$rc" 'release files do not share writable inode metadata with the package store'

if bun -e 'await import(process.argv[1])' "$release/collector/src/requests/requests-store.ts" \
  >"$TESTROOT/import.log" 2>&1; then rc=0; else tail -c 800 "$TESTROOT/import.log"; rc=1; fi
check "$rc" 'release-local collector imports resolve without the mutable checkout'

escaping=$(python3 - "$release" <<'PY'
import os
import pathlib
import sys
root = pathlib.Path(sys.argv[1]).resolve(strict=True)
bad = []
for directory, names, files in os.walk(root, followlinks=False):
    for name in [*names, *files]:
        path = pathlib.Path(directory) / name
        if path.is_symlink():
            try:
                path.resolve(strict=True).relative_to(root)
            except (OSError, ValueError):
                bad.append(str(path))
print("\n".join(bad))
PY
)
if [[ -z "$escaping" ]]; then rc=0; else rc=1; fi
check "$rc" 'all runtime dependency links stay inside the release'

cat >"$BIN/bun" <<'SH'
#!/usr/bin/env bash
printf 'sha=%s\nidentity=%s\nargv=%s\n' "$OVERDECK_DEPLOY_SHA" "${OVERDECK_DEPLOYMENT_IDENTITY:-}" "$*" >"$RUNTIME_LOG"
SH
chmod +x "$BIN/bun"
RUNTIME_LOG="$LOG" OVERDECK_BUN_BIN="$BIN/bun" "$release/bin/start"
if grep -qx "sha=$SHA" "$LOG" \
  && grep -qx "argv=run $release/collector/src/index.ts" "$LOG"; then rc=0; else rc=1; fi
check "$rc" 'the artifact launcher derives runtime identity from its immutable manifest'

second=$(OVERDECK_DEPLOY_DIR="$ROOT" OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" \
  OVERDECK_BACKEND_RELEASE_TOOL="$RELEASE_TOOL" bash "$SCRIPT" collector "$SHA")
if [[ "$second" == "$release" ]]; then rc=0; else rc=1; fi
check "$rc" 'staging the same revision reuses its validated release'

controller_release=$(OVERDECK_DEPLOY_DIR="$ROOT" OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" \
  OVERDECK_BACKEND_RELEASE_TOOL="$RELEASE_TOOL" bash "$SCRIPT" controller "$SHA")
RUNTIME_LOG="$LOG" OVERDECK_BUN_BIN="$BIN/bun" "$controller_release/bin/start"
TREE=$(git -C "$ROOT" rev-parse "${SHA}^{tree}")
if [[ "$controller_release" == "$BACKEND/controller/releases/$SHA" ]] \
  && OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" bash "$RELEASE_TOOL" validate controller "$SHA" \
  && [[ ! -w "$controller_release/controller/src/index.ts" ]] \
  && [[ -f "$controller_release/modules/workstation/claude/workflows/lib/finish-branch.sh" ]] \
  && [[ -f "$controller_release/modules/workstation/claude/workflows/hooks/land-guard.pre-push" ]] \
  && [[ -z "$(find "$controller_release" -type f -links +1 -print -quit)" ]] \
  && python3 - "$controller_release/deployment-identity.json" "$SHA" "$TREE" <<'PY'
import json
import re
import sys

with open(sys.argv[1], "r", encoding="utf-8") as stream:
    value = json.load(stream)
good = (
    value.get("deploymentId") == f"controller-{sys.argv[2]}"
    and value.get("targetId") == "controller"
    and value.get("deployedSha") == sys.argv[2]
    and value.get("deployedTree") == sys.argv[3]
    and isinstance(value.get("artifactDigest"), str)
    and re.fullmatch(r"[0-9a-f]{64}", value["artifactDigest"]) is not None
)
raise SystemExit(0 if good else 1)
PY
then
  if grep -qx "sha=$SHA" "$LOG" \
    && grep -qx "identity=$controller_release/deployment-identity.json" "$LOG" \
    && grep -qx "argv=run $controller_release/controller/src/index.ts" "$LOG"; then rc=0; else rc=1; fi
else
  rc=1
fi
check "$rc" 'an exact Git revision becomes a self-contained controller release'

botmaster_release=$(OVERDECK_DEPLOY_DIR="$ROOT" OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" \
  OVERDECK_BACKEND_RELEASE_TOOL="$RELEASE_TOOL" bash "$SCRIPT" botmaster-proxy "$SHA")
RUNTIME_LOG="$LOG" OVERDECK_BUN_BIN="$BIN/bun" "$botmaster_release/bin/start"
if [[ "$botmaster_release" == "$BACKEND/botmaster-proxy/releases/$SHA" ]] \
  && OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" bash "$RELEASE_TOOL" validate botmaster-proxy "$SHA" \
  && [[ -f "$botmaster_release/packaging/botmaster-proxy.ts" ]] \
  && [[ -f "$botmaster_release/modules/botmaster/notify/store.ts" ]] \
  && [[ -z "$(find "$botmaster_release" -type f -links +1 -print -quit)" ]] \
  && grep -qx "sha=$SHA" "$LOG" \
  && grep -qx "argv=run $botmaster_release/packaging/botmaster-proxy.ts" "$LOG"; then rc=0; else rc=1; fi
check "$rc" 'an exact Git revision becomes a self-contained Botmaster proxy release'

cat >"$BIN/node" <<'SH'
#!/usr/bin/env bash
printf 'sha=%s\nargv=%s\n' "$OVERDECK_DEPLOY_SHA" "$*" >"$RUNTIME_LOG"
SH
chmod +x "$BIN/node"
gateway_release=$(OVERDECK_DEPLOY_DIR="$ROOT" OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" \
  OVERDECK_BACKEND_RELEASE_TOOL="$RELEASE_TOOL" bash "$SCRIPT" actions-gateway "$SHA")
RUNTIME_LOG="$LOG" OVERDECK_NODE_BIN="$BIN/node" "$gateway_release/bin/start"
if [[ "$gateway_release" == "$BACKEND/actions-gateway/releases/$SHA" ]] \
  && OVERDECK_BACKEND_RELEASE_ROOT="$BACKEND" bash "$RELEASE_TOOL" validate actions-gateway "$SHA" \
  && [[ -f "$gateway_release/actions-gateway/dist/src/server.js" ]] \
  && [[ -f "$gateway_release/actions-gateway/package.json" ]] \
  && [[ -z "$(find "$gateway_release" -type f -links +1 -print -quit)" ]] \
  && grep -qx "sha=$SHA" "$LOG" \
  && grep -qx "argv=$gateway_release/actions-gateway/dist/src/server.js" "$LOG"; then rc=0; else rc=1; fi
check "$rc" 'an exact Git revision becomes a compiled self-contained Actions Gateway release'

(( fails == 0 )) || { printf '%s check(s) failed\n' "$fails" >&2; exit 1; }
printf 'stage-backend-release: all checks passed\n'
