#!/usr/bin/env bash
# Hermetic provisioning test. ssh and rsync are stubs, so no buildbox is contacted.
set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSTATION_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PROVISION="$WORKSTATION_DIR/bin/sandbox-provision"
SANDBOX_DIR="$(cd "$WORKSTATION_DIR/../../sandbox" && pwd)"
ROOT="$(mktemp -d)"
trap 'rm -rf "$ROOT"' EXIT

make_expected_tags() {
  local stage hash
  stage="$ROOT/image-context"
  mkdir -p "$stage/lib"
  cp -r "$SANDBOX_DIR/image/." "$stage/"
  cp "$SANDBOX_DIR/lib/sandbox-payload.mjs" "$stage/lib/"
  cp "$WORKSTATION_DIR/lib/e2e-pair.sh" "$stage/lib/"
  # shellcheck source=../../sandbox/host/lib/image-context.sh
  . "$SANDBOX_DIR/host/lib/image-context.sh"
  hash="$(sandbox_image_context_hash "$stage")"
  EXPECTED_TAG="localhost/overdeck-agent-sandbox:$hash"
  EXPECTED_E2E_TAG="localhost/overdeck-agent-sandbox-e2e:$hash"
}

make_stubs() {
  mkdir -p "$ROOT/bin" "$ROOT/home/.ssh"
  cat >"$ROOT/bin/ssh" <<'SH'
#!/usr/bin/env bash
set -u
host=""
for arg in "$@"; do
  case "$arg" in healthy-one|broken-box|healthy-two) host="$arg" ;; esac
done
case " $* " in
  *" -G "*) printf 'port 22\n'; exit 0 ;;
esac
if [ "$host" = broken-box ]; then
  printf 'ssh: Could not resolve hostname broken-box\n' >&2
  exit 255
fi
case "${!#}" in
  *bash\ -s)
    remote="$(cat)"
    if grep -qF 'registry pull miss; falling back to local build' <<<"$remote"; then
      printf 'sandbox-provision: registry pull miss; falling back to local build\n' >&2
    fi
    ;;
  *agent-image-tag) printf '%s\n' "$EXPECTED_TAG" ;;
  *e2e-image-tag) printf '%s\n' "$EXPECTED_E2E_TAG" ;;
esac
SH
  cat >"$ROOT/bin/rsync" <<'SH'
#!/usr/bin/env bash
exit 0
SH
  chmod +x "$ROOT/bin/ssh" "$ROOT/bin/rsync"
}

make_expected_tags
make_stubs

set +e
output="$(env HOME="$ROOT/home" PATH="$ROOT/bin:$PATH" EXPECTED_TAG="$EXPECTED_TAG" \
  EXPECTED_E2E_TAG="$EXPECTED_E2E_TAG" bash "$PROVISION" \
  --host healthy-one --host broken-box --host healthy-two 2>&1)"
rc=$?
set -e

if [ "$rc" -ne 0 ] \
  && grep -qF 'sandbox-provision: broken-box failed during probe' <<<"$output" \
  && grep -qF 'sandbox-provision: registry pull miss; falling back to local build' <<<"$output" \
  && grep -qF "sandbox-provision: healthy-one provisioned ($EXPECTED_TAG)" <<<"$output" \
  && grep -qF "sandbox-provision: healthy-two provisioned ($EXPECTED_TAG)" <<<"$output"; then
  printf 'PASS registry pull miss names the local-build fallback and a failed box is named while the remaining boxes converge\n'
  exit 0
fi

printf 'FAIL failure honesty (rc=%s)\n%s\n' "$rc" "$output" >&2
exit 1
