#!/usr/bin/env bash
# Behaviour test for with-inline-diag.sh: whatever sandcat does, the wrapped
# command must still run, under `set -eo pipefail` as the e2e phases use.

set -uo pipefail

DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
WRAPPER="${DIR}/with-inline-diag.sh"
REPO_ROOT=$(cd "${DIR}/../../.." && pwd)
TEST_ROOT=$(mktemp -d)
trap 'rm -rf "${TEST_ROOT}"' EXIT
pass=0
fail=0

run() {
  local name="$1"
  shift
  local out rc
  out=$(env -i PATH="/usr/bin:/bin" HOME="${HOME}" KUBECONFIG=/tmp/kubeconfig \
    CALICO_MCP_LOCAL_BIN="${CALICO_MCP_LOCAL_BIN}" \
    SANDCAT_PR_CONTEXT_FILE="${SANDCAT_PR_CONTEXT_FILE}" \
    "$@" \
    bash -eo pipefail -c "'${WRAPPER}' echo WRAPPED-COMMAND-RAN" 2>&1)
  rc=$?
  if [[ "${rc}" == 0 ]] && grep -qF WRAPPED-COMMAND-RAN <<<"${out}"; then
    echo "PASS ${name}"
    pass=$((pass + 1))
  else
    echo "FAIL ${name} (rc=${rc})"
    sed 's/^/    /' <<<"${out}"
    fail=$((fail + 1))
  fi
}

newhome() {
  HOME=$(mktemp -d -p "${TEST_ROOT}")
  export HOME
  mkdir -p "${HOME}/.local/bin"
  CALICO_MCP_LOCAL_BIN="${HOME}/.local/bin/calico-mcp"
  export CALICO_MCP_LOCAL_BIN
  SANDCAT_PR_CONTEXT_FILE="${HOME}/pr-context.json"
  export SANDCAT_PR_CONTEXT_FILE
  printf '#!/bin/sh\necho "calico-mcp 0.0-stub"\n' > "${CALICO_MCP_LOCAL_BIN}"
  chmod +x "${CALICO_MCP_LOCAL_BIN}"
}

newhome
cat > "${HOME}/.local/bin/sandcat" <<'STUB'
#!/usr/bin/env bash
case "$1" in
  # As chatty on stdout as the real one: this is what must not reach the eval.
  check-mcp) echo "calico-mcp ok: 18 tools registered, cluster answered"; exit 0 ;;
  fetch-pr)
    out=""
    while [[ $# -gt 0 ]]; do
      [[ "$1" == "--out" ]] && out="$2"
      shift
    done
    echo '{"body":"stub"}' > "${out}"
    ;;
  *) exit 0 ;;
esac
STUB
chmod +x "${HOME}/.local/bin/sandcat"
run "everything set up" SANDCAT_GEMINI_KEY=key-a

# The ordinary local case, and any job not granted a key.
newhome
run "no Gemini key"

newhome
cat > "${HOME}/.local/bin/sandcat" <<'STUB'
#!/usr/bin/env bash
[[ "$1" == "check-mcp" ]] && exit 3
exit 1
STUB
chmod +x "${HOME}/.local/bin/sandcat"
run "calico-mcp refused" SANDCAT_GEMINI_KEY=key-a

newhome
run "sandcat binary unavailable" SANDCAT_GEMINI_KEY=key-a

# A stray line on the payload stream must degrade to "no diagnosis".
newhome
cat > "${HOME}/.local/bin/sandcat" <<'STUB'
#!/usr/bin/env bash
echo "surprise: not an assignment; and (unbalanced"
exit 0
STUB
chmod +x "${HOME}/.local/bin/sandcat"
run "sandcat writes junk to stdout" SANDCAT_GEMINI_KEY=key-a

newhome
if env -i PATH="/usr/bin:/bin" HOME="${HOME}" KUBECONFIG=/tmp/kubeconfig \
    bash -eo pipefail -c "'${WRAPPER}'" >/dev/null 2>&1; then
  echo "FAIL no command: exited 0 having run nothing"
  fail=$((fail + 1))
else
  echo "PASS no command: refuses instead of silently succeeding"
  pass=$((pass + 1))
fi

# Each kind e2e target must still carry the wrapper, or its lane loses inline diagnosis.
recipe_of() {
  awk -v target="$1" '
    $0 ~ "^"target":" { in_recipe = 1; next }
    in_recipe && /^\t/ { print; next }
    in_recipe && NF && !/^#/ { exit }
  ' "${REPO_ROOT}/Makefile"
}

for target in e2e-test e2e-test-bpf; do
  if recipe_of "${target}" | grep -qF 'E2E_RUN_WRAPPER'; then
    echo "PASS ${target} applies \$(E2E_RUN_WRAPPER)"
    pass=$((pass + 1))
  else
    echo "FAIL ${target} does not apply \$(E2E_RUN_WRAPPER): inline diagnosis is off in that lane"
    fail=$((fail + 1))
  fi
done

# sandcat reads the test selection from the ginkgo environment and accepts only repo-relative paths.
check_config_env() {
  local name="$1" want="$2"
  shift 2
  local got
  got=$(make -s -n -C "${REPO_ROOT}" e2e-run KUBECONFIG=/tmp/kubeconfig "$@" 2>/dev/null |
    grep -F ./bin/ginkgo | grep -oE 'E2E_TEST_CONFIG="[^"]*"')
  if [[ "${got}" == "E2E_TEST_CONFIG=\"${want}\"" ]]; then
    echo "PASS ${name}"
    pass=$((pass + 1))
  else
    echo "FAIL ${name}: got '${got}', want E2E_TEST_CONFIG=\"${want}\""
    fail=$((fail + 1))
  fi
}

check_config_env "e2e-run exports the default selection" e2e/config/kind/conformance.yaml
check_config_env "e2e-run exports an absolute selection repo-relative" e2e/config/kind/bpf.yaml \
  E2E_TEST_CONFIG="${REPO_ROOT}/e2e/config/kind/bpf.yaml"
check_config_env "e2e-run exports a short selection repo-relative" e2e/config/kind/bpf.yaml \
  E2E_TEST_CONFIG=kind/bpf.yaml

echo "=== ${pass} passed, ${fail} failed"
[[ "${fail}" == 0 ]]
