#!/usr/bin/env bash
# Sentinel regression for hack/verify-install.sh: the install smoke must
# never read/write the ambient kubeconfig, must not invoke Helm unless the
# Kind cluster was actually created, and every kind/helm call (including
# cleanup delete) must pass the run's own temp kubeconfig explicitly.
#
# Run from the module root (internal/capacity-planner).
set -euo pipefail

cd "$(dirname "$0")/.."

SENTINEL=$(mktemp)
SENTINEL_ORIG=$(mktemp)
HELM_LOG=$(mktemp)
KIND_LOG=$(mktemp)
HELM_STUB=$(mktemp)
KIND_STUB=$(mktemp)
trap 'rm -f "$SENTINEL" "$SENTINEL_ORIG" "$HELM_LOG" "$KIND_LOG" "$HELM_STUB" "$KIND_STUB"' EXIT

# Independent sentinel kubeconfig with a distinct current-context.
cat > "$SENTINEL" <<'EOF'
apiVersion: v1
kind: Config
clusters:
- cluster:
    server: https://sentinel.invalid
  name: sentinel-cluster
contexts:
- context:
    cluster: sentinel-cluster
    user: sentinel-user
  name: sentinel-context
current-context: sentinel-context
users:
- name: sentinel-user
  user: {}
EOF
cp "$SENTINEL" "$SENTINEL_ORIG"

# Helm stub: records every invocation instead of acting on any cluster.
cat > "$HELM_STUB" <<EOF
#!/bin/sh
echo "\$@" >> "$HELM_LOG"
EOF
chmod +x "$HELM_STUB"

# Kind stub: records every invocation and fails at the create stage, so the
# cluster is never created and cleanup still runs (delete + rmi + temp file
# removal) on the failure path.
cat > "$KIND_STUB" <<EOF
#!/bin/sh
echo "\$@" >> "$KIND_LOG"
exit 1
EOF
chmod +x "$KIND_STUB"

set +e
KIND="$KIND_STUB" \
HELM="$HELM_STUB" \
CONTAINER_TOOL=/bin/false \
KIND_NODE_IMAGE="kindest/node:v1.36.1@sha256:3489c7674813ba5d8b1a9977baea8a6e553784dab7b84759d1014dbd78f7ebd5" \
VERSION="v0.0.0" \
COMMIT="unknown" \
KUBECONFIG="$SENTINEL" \
hack/verify-install.sh >/dev/null 2>&1
rc=$?
set -e

if [ "$rc" = "0" ]; then
  echo "test/verify-install: expected a failure at Kind create, got success" >&2
  exit 1
fi

if ! cmp -s "$SENTINEL" "$SENTINEL_ORIG"; then
  echo "test/verify-install: ambient kubeconfig was modified" >&2
  exit 1
fi

if [ -s "$HELM_LOG" ]; then
  echo "test/verify-install: Helm was invoked without a created cluster: $(cat "$HELM_LOG")" >&2
  exit 1
fi

# The failure path must still run `kind delete cluster` with the run's own
# temp kubeconfig - never the sentinel.
DELETE_LINE=$(grep 'delete cluster' "$KIND_LOG" || true)
if [ -z "$DELETE_LINE" ]; then
  echo "test/verify-install: cleanup did not call kind delete cluster" >&2
  exit 1
fi
DELETE_KC=$(printf '%s\n' "$DELETE_LINE" | sed -n 's/.*--kubeconfig \([^ ]*\).*/\1/p')
if [ -z "$DELETE_KC" ]; then
  echo "test/verify-install: kind delete cluster is missing --kubeconfig: $DELETE_LINE" >&2
  exit 1
fi
if [ "$DELETE_KC" = "$SENTINEL" ]; then
  echo "test/verify-install: kind delete cluster used the ambient kubeconfig: $DELETE_LINE" >&2
  exit 1
fi

echo "test/verify-install: OK (sentinel untouched, no Helm call, delete uses temp kubeconfig)"
