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

ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../../.." && pwd -P)"
DISPATCH="$ROOT/modules/workstation/claude/bin/e2e-k8s-dispatch"
JOB="$ROOT/modules/workstation/claude/lib/e2e-k8s/job.yaml"
work="$(mktemp -d)"
trap 'rm -rf -- "$work"' EXIT
marker="$work/remote.marker"
: >"$marker"
mkdir -p "$work/bin" "$work/not-git" "$work/repo"

for command in ssh kubectl; do
    cat >"$work/bin/$command" <<EOF
#!/usr/bin/env bash
printf '%s\n' '$command' >>'$marker'
exit 99
EOF
    chmod +x "$work/bin/$command"
done

set +e
output="$(cd "$work/not-git" && timeout 9 env \
    PATH="$work/bin:$PATH" \
    IPZ_E2E_SSH_BIN="$work/bin/ssh" \
    IPZ_E2E_RUNNER_IMAGE=localhost/test:1 \
    IPZ_E2E_SNAPSHOT_DIR=/snapshot \
    "$DISPATCH" freshness-test mirror-slug debian1 -- /bin/true 2>&1)"
status=$?
set -e
[[ $status -eq 6 ]] || { printf 'expected non-git admission 6, got %s\n%s\n' "$status" "$output" >&2; exit 1; }
[[ "$output" == *'not a git repository with a resolvable HEAD'* ]] || { printf 'missing non-git diagnostic\n%s\n' "$output" >&2; exit 1; }
[[ ! -s "$marker" ]] || { printf 'non-git rejection attempted remote access: %s\n' "$(<"$marker")" >&2; exit 1; }

git -C "$work/repo" init -q
git -C "$work/repo" config user.email test@example.invalid
git -C "$work/repo" config user.name Test
printf 'fresh\n' >"$work/repo/file"
git -C "$work/repo" add file
git -C "$work/repo" commit -qm initial
expected="$(git -C "$work/repo" rev-parse HEAD)"

# Manifest-render seam: assert the template token and the dispatcher's explicit
# token/value substitution pair, then exercise that same literal replacement.
grep -q 'value: "__EXPECTED_COMMIT__"' "$JOB"
grep -q '"__EXPECTED_COMMIT__": expected_commit' "$DISPATCH"
python3 - "$JOB" "$expected" <<'PY'
import re
import sys
from pathlib import Path
text = Path(sys.argv[1]).read_text(encoding="utf-8")
rendered = text.replace("__EXPECTED_COMMIT__", sys.argv[2])
pattern = rf'- name: IPZ_E2E_EXPECTED_COMMIT\n\s+value: "{re.escape(sys.argv[2])}"'
if not re.search(pattern, rendered):
    raise SystemExit("rendered manifest lacks expected commit environment value")
PY

stage_line="$(grep -n -- '- name: stage-mirror' "$JOB" | cut -d: -f1)"
fresh_line="$(grep -n -- '- name: verify-mirror-revision' "$JOB" | cut -d: -f1)"
provision_line="$(grep -n -- '- name: configure-wordpress' "$JOB" | cut -d: -f1)"
[[ $stage_line -lt $fresh_line && $fresh_line -lt $provision_line ]] || {
    printf 'freshness init container is not between staging and provisioning\n' >&2
    exit 1
}
grep -q 'exit 42' "$JOB"
grep -q 'IPZ_E2E_MIRROR_FRESHNESS expected=%s actual=%s node=%s' "$JOB"

if grep -Eq '(^|[;&|[:space:]])(git[[:space:]]+push|rsync|scp)([[:space:]]|$)' "$DISPATCH"; then
    printf 'dispatcher contains a forbidden mirror repair invocation\n' >&2
    exit 1
fi

bash -n "$DISPATCH"
printf 'e2e-k8s-dispatch freshness tests passed\n'
