#!/usr/bin/env bash
# item_vendor places release artifacts nothing can clone or build. Exercised against a
# throwaway HOME and a file:// tarball standing in for the vendor CDN, so the audit verdicts
# and the bootstrap convergence are checked without touching the fleet or the network.
set -euo pipefail

CHECKS="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/lib/buildbox-checks.sh"
DEVTOOLS="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/devtools.json"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
fail=0
check() { [ "$2" = "$3" ] && printf 'ok   %s\n' "$1" || { printf 'FAIL %s\n  want: %s\n  got:  %s\n' "$1" "$2" "$3"; fail=1; }; }

# One tarball per version, laid out the way a vendor ships one: a single top-level directory
# the extract strips, holding the executable.
pack() {
  local v="$1"
  local d="$WORK/pkg-$v"
  mkdir -p "$d/agent"
  printf '#!/bin/sh\necho probe %s\n' "$v" > "$d/agent/probe"
  chmod 755 "$d/agent/probe"
  tar -czf "$WORK/probe-$v.tar.gz" -C "$d" agent
}
pack 1.0.0
pack 2.0.0

decl() {
  printf '{"tools":[],"vendor":[{"name":"probe","kind":"tarball","version":"%s","version_cmd":"probe","url":"file://%s/probe-{version}.tar.gz","dest":"~/.vendor/probe/{version}","bins":{"probe":"{dest}/probe"}}]}' "$1" "$WORK"
}

run() { # $1=mode $2=version
  HOME="$WORK/home" DEVTOOLS_B64=$(decl "$2" | base64 -w0) \
    bash "$CHECKS" "$1" 2>/dev/null | grep -E '(^| )probe ' || true
}

mkdir -p "$WORK/home"
check "pi is a mise-managed vendor" "npm:@earendil-works/pi-coding-agent@0.80.3" "$(jq -r '.vendor[] | select(.name == "pi") | "\(.tool)@\(.version)"' "$DEVTOOLS")"
check "absent box reports drift" "DRIFT probe" "$(run audit 1.0.0 | awk '{print $1, $2}')"

run bootstrap 1.0.0 >/dev/null
check "bootstrap places the pinned artifact" "yes" "$([ -x "$WORK/home/.vendor/probe/1.0.0/probe" ] && echo yes)"
check "bootstrap links the declared bin" "$WORK/home/.vendor/probe/1.0.0/probe" "$(readlink "$WORK/home/.local/bin/probe")"
check "converged box audits clean" "OK probe 1.0.0" "$(run audit 1.0.0 | awk '{print $1, $2, $3}')"

# A version bump is drift even though the old release is installed and on PATH — the box
# answers `command -v` either way, so only the reported version separates them.
check "version bump reports drift" "DRIFT probe" "$(run audit 2.0.0 | awk '{print $1, $2}')"
run bootstrap 2.0.0 >/dev/null
check "version bump converges" "OK probe 2.0.0" "$(run audit 2.0.0 | awk '{print $1, $2, $3}')"
check "version bump repoints the link" "$WORK/home/.vendor/probe/2.0.0/probe" "$(readlink "$WORK/home/.local/bin/probe")"

# A link hand-pointed back at the old release must not audit clean just because the new
# release exists on disk.
ln -sfn "$WORK/home/.vendor/probe/1.0.0/probe" "$WORK/home/.local/bin/probe"
check "stale link reports drift" "DRIFT probe" "$(run audit 2.0.0 | awk '{print $1, $2}')"

# An unreachable artifact must fail closed, not leave a half-extracted directory behind.
bad=$(printf '{"tools":[],"vendor":[{"name":"probe","kind":"tarball","version":"9.9.9","version_cmd":"probe","url":"file://%s/absent.tar.gz","dest":"~/.vendor/probe/{version}","bins":{"probe":"{dest}/probe"}}]}' "$WORK")
out=$(HOME="$WORK/home" DEVTOOLS_B64=$(printf %s "$bad" | base64 -w0) bash "$CHECKS" bootstrap 2>/dev/null | grep -E '(^| )probe ' || true)
check "unreachable artifact reports drift" "DRIFT probe" "$(printf %s "$out" | awk '{print $1, $2}')"
check "failed fetch leaves no partial dir" "gone" "$([ -e "$WORK/home/.vendor/probe/9.9.9" ] && echo present || echo gone)"
check "failed fetch leaves no staging dir" "" "$(ls "$WORK/home/.vendor/probe" | grep '^\.tmp' || true)"

# A kind no branch handles must fail closed rather than fall through to the link step and
# report the tool converged.
odd=$(printf '{"tools":[],"vendor":[{"name":"probe","kind":"apt","version":"1.0.0","version_cmd":"probe-absent","bins":{"probe":"~/nowhere"}}]}')
out=$(HOME="$WORK/home" DEVTOOLS_B64=$(printf %s "$odd" | base64 -w0) bash "$CHECKS" bootstrap 2>/dev/null | grep -E '(^| )probe ' || true)
check "unknown kind reports drift" "DRIFT probe unknown vendor kind: apt" "$(printf %s "$out" | sed 's/  */ /g')"

# A declaration with no vendor entries is silent, so boxes predating the key audit unchanged.
none=$(HOME="$WORK/home" DEVTOOLS_B64=$(printf '{"tools":[]}' | base64 -w0) bash "$CHECKS" audit 2>/dev/null | grep -c 'vendor' || true)
check "no vendor key emits nothing" "0" "$none"

exit "$fail"
