#!/usr/bin/env bash
# Self-test of the repository-owned contract boundary. It needs no simulator and no
# network. Run: .sdkharness/tests/selftest
#
# What it pins: (1) a dispatcher turns a child that prints COULD-NOT-RUN/SKIP and then
# exits nonzero into FAIL, not into amber evidence; (2) a check run directly refuses a
# non-simulator target and any non-loopback URL; (3) with a Go toolchain, the standard
# transport refuses a non-loopback connection; (4) a build failure is only amber when the
# Go toolchain is missing or too old: a checkout or check that does not compile is a FAIL.
set -u
HERE="$(cd "$(dirname "$0")" && pwd -P)"
TMP="$(mktemp -d "${TMPDIR:-/tmp}/blazer-selftest.XXXXXX")" || exit 1
trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0
ok() { PASS=$((PASS + 1)); printf '[PASS] %s\n' "$1"; }
bad() { FAIL=$((FAIL + 1)); printf '[FAIL] %s\n' "$1"; }
LOOP=http://127.0.0.1:9

# --- (1) dispatcher contract with fixture children -------------------------------
mkdir -p "$TMP/t/lib" "$TMP/t/conformance" "$TMP/t/resilience" "$TMP/t/health"
cp "$HERE"/run-conformance "$HERE"/run-resilience "$HERE"/run-health "$TMP/t/"
cp "$HERE"/lib/contract.sh "$TMP/t/lib/"
fixture() { # <path> <say line> <exit code>
  printf '#!/usr/bin/env bash\nprintf "%%s\\n" %q\nexit %s\n' "$2" "$3" > "$1"; chmod +x "$1"
}
run_disp() { # <level> <scenario> -> stdout of dispatcher; exit status in $TMP/rc
  env -i PATH="$PATH" SDKHARNESS_TEST_LEVEL="$1" SDKHARNESS_SCENARIO="$2" \
    SDKHARNESS_SIMULATOR_URL="$LOOP" SDKHARNESS_SIMULATOR_CONTROL_URL="$LOOP" \
    "$TMP/t/run-$1" 2>/dev/null
  printf '%s' "$?" > "$TMP/rc"
}
for spec in "conformance|CONFORMANCE blazer" "resilience|RESILIENCE blazer"; do
  level="${spec%%|*}"; head="${spec#*|}"
  fixture "$TMP/t/$level/fx.cnr_ok" "$head fx.cnr_ok @simulator: COULD-NOT-RUN (x -- nothing to do)" 0
  fixture "$TMP/t/$level/fx.cnr_bad" "$head fx.cnr_bad @simulator: COULD-NOT-RUN (x -- nothing to do)" 3
  out="$(run_disp "$level" fx.cnr_ok)"; RC="$(cat "$TMP/rc")"
  case "$out" in *"	SKIP	"*) [ "$RC" = 0 ] && ok "$level: COULD-NOT-RUN with exit 0 is amber (SKIP)" || bad "$level: clean CNR exited $RC";; *) bad "$level: clean CNR not SKIP ($out)";; esac
  out="$(run_disp "$level" fx.cnr_bad)"; RC="$(cat "$TMP/rc")"
  case "$out" in *"	FAIL	"*"COULD-NOT-RUN exited 3"*) [ "$RC" = 1 ] && ok "$level: COULD-NOT-RUN with a nonzero exit is a FAIL" || bad "$level: CNR+nonzero exited $RC, want 1";; *) bad "$level: CNR+nonzero not FAIL ($out)";; esac
done
fixture "$TMP/t/health/golden-path" "HEALTHCHECK blazer: SKIP (x)" 4
out="$(env -i PATH="$PATH" SDKHARNESS_TEST_LEVEL=health SDKHARNESS_SCENARIO=golden-path SDKHARNESS_SIMULATOR_URL="$LOOP" "$TMP/t/run-health" 2>/dev/null)"; rc=$?
case "$out" in *"	FAIL	"*"SKIP exited 4"*) [ "$rc" = 1 ] && ok "health: SKIP with a nonzero exit is a FAIL" || bad "health: exit $rc";; *) bad "health: SKIP+nonzero not FAIL ($out)";; esac
# the health dispatcher must hand the check only the simulator's credential
cat > "$TMP/t/health/golden-path" <<'FX'
#!/usr/bin/env bash
printf 'HEALTHCHECK blazer: FAIL (%s|%s|%s)\n' "${B2_APPLICATION_KEY_ID:-}" "${B2_APPLICATION_KEY:-}" "${B2_REAL_ONLY:-unset}"
exit 1
FX
chmod +x "$TMP/t/health/golden-path"
out="$(env -i PATH="$PATH" B2_REAL_ONLY=secret B2_APPLICATION_KEY_ID=AKIAREAL B2_APPLICATION_KEY=realkey SDKHARNESS_TEST_LEVEL=health SDKHARNESS_SCENARIO=golden-path SDKHARNESS_SIMULATOR_URL="$LOOP" "$TMP/t/run-health" 2>/dev/null)"
case "$out" in *"test-key-id|test-key|unset"*) ok "health: ambient B2_* are replaced by the simulator's fixed credential";; *) bad "health: ambient credential leaked ($out)";; esac

# --- (2) a leaf run directly refuses anything but the loopback simulator ---------
refuse() { # <label> <leaf> <expect> env...
  local label="$1" leaf="$2" expect="$3"; shift 3
  out="$(env -i PATH="$PATH" "$@" "$HERE/$leaf" 2>&1)"; rc=$?
  case "$out" in *"FAIL ("*"$expect"*) [ "$rc" = 1 ] && ok "$label" || bad "$label (exit $rc)";; *) bad "$label ($out)";; esac
}
refuse "conformance leaf: CONFORMANCE_TARGET=staging is refused" conformance/files.upload "only the loopback simulator" CONFORMANCE_TARGET=staging CONFORMANCE_SIMULATOR_URL="$LOOP"
refuse "conformance leaf: CONFORMANCE_TARGET=production is refused" conformance/files.upload "only the loopback simulator" CONFORMANCE_TARGET=production CONFORMANCE_SIMULATOR_URL="$LOOP"
refuse "conformance leaf: an external URL is refused" conformance/files.upload "CONFORMANCE_SIMULATOR_URL must be an IPv4 loopback" CONFORMANCE_SIMULATOR_URL=https://api.backblaze.net
refuse "conformance leaf: no URL is refused (no default realm)" conformance/files.upload "CONFORMANCE_SIMULATOR_URL must be an IPv4 loopback"
refuse "resilience leaf: an external control URL is refused" resilience/upload.retry_408 "RESILIENCE_CONTROL_URL must be an IPv4 loopback" RESILIENCE_SIMULATOR_URL="$LOOP" RESILIENCE_CONTROL_URL=https://api.backblaze.net
refuse "health leaf: no realm is refused (no production default)" health/golden-path "HEALTHCHECK_REALM_URL must be an IPv4 loopback"
refuse "health leaf: a real credential is refused" health/golden-path "only the simulator's fixed test credential" HEALTHCHECK_REALM_URL="$LOOP" B2_TEST_APPLICATION_KEY_ID=x B2_APPLICATION_KEY_ID=AKIAREAL B2_APPLICATION_KEY=realkey

# --- (3) the Go transport guard ---------------------------------------------------
if command -v go >/dev/null 2>&1; then
  mkdir -p "$TMP/g" && cp "$HERE/lib/loopback_guard.go.txt" "$TMP/g/loopback_guard.go"
  printf 'module guardtest\n\ngo 1.18\n' > "$TMP/g/go.mod"
  cat > "$TMP/g/main.go" <<'GO'
package main

import (
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	_, err := http.Get("http://192.0.2.1:9/")
	if err == nil || !strings.Contains(err.Error(), "refusing non-loopback") {
		fmt.Println("external connection not refused:", err)
		os.Exit(1)
	}
	_, err = http.Get("http://127.0.0.1:1/")
	if err != nil && strings.Contains(err.Error(), "refusing non-loopback") {
		fmt.Println("loopback wrongly refused:", err)
		os.Exit(1)
	}
	fmt.Println("guard ok")
}
GO
  if (cd "$TMP/g" && GOPROXY=off GOFLAGS=-mod=mod GOTOOLCHAIN=local GOWORK=off go run . >/dev/null 2>&1); then
    ok "go: the standard transport refuses a non-loopback connection and allows loopback"
  else
    bad "go: the loopback transport guard does not hold"
  fi
else
  printf '[SKIP] go: toolchain not on PATH; transport guard not exercised\n'
fi


# --- (4) a build failure is amber ONLY for a missing/unusable toolchain ----------
# Each case runs a REAL leaf (and the health check) inside a throwaway fake checkout, so the
# path under test is the one the harness takes: leaf -> sdkharness_go_build -> verdict.
mk_tree() { # <dir> <go directive> <b2 package source>
  local d="$1"
  mkdir -p "$d/.sdkharness/tests/conformance" "$d/.sdkharness/tests/resilience" "$d/.sdkharness/tests/health" "$d/.sdkharness/tests/lib" "$d/b2"
  cp "$HERE/lib/contract.sh" "$HERE/lib/loopback_guard.go.txt" "$d/.sdkharness/tests/lib/"
  cp "$HERE/conformance/files.upload" "$d/.sdkharness/tests/conformance/"
  cp "$HERE/resilience/upload.retry_503" "$d/.sdkharness/tests/resilience/"
  cp "$HERE/health/golden-path" "$d/.sdkharness/tests/health/"
  printf 'module github.com/Backblaze/blazer\n\ngo %s\n' "$2" > "$d/go.mod"
  printf '%s\n' "$3" > "$d/b2/b2.go"
}
# env -i would also strip HOME/GOCACHE, and Go then refuses to build for a reason unrelated to
# what each case pins; hand the compiler its caches explicitly.
gocaches() { printf 'HOME=%s GOCACHE=%s GOMODCACHE=%s' "${HOME:-/nonexistent}" "$(go env GOCACHE 2>/dev/null)" "$(go env GOMODCACHE 2>/dev/null)"; }
leaf_out() { # <tree> <level> -> output; exit status in $TMP/rc
  local t="$1" lvl="$2" gc; gc="$(gocaches)"
  case "$lvl" in
    conformance) out="$(env -i PATH="$PATH" $gc CONFORMANCE_TARGET=simulator CONFORMANCE_SIMULATOR_URL="$LOOP" "$t/.sdkharness/tests/conformance/files.upload" 2>&1)" ;;
    resilience)  out="$(env -i PATH="$PATH" $gc RESILIENCE_SIMULATOR_URL="$LOOP" RESILIENCE_CONTROL_URL="$LOOP" "$t/.sdkharness/tests/resilience/upload.retry_503" 2>&1)" ;;
    health)      out="$(env -i PATH="$PATH" $gc HEALTHCHECK_REALM_URL="$LOOP" B2_TEST_APPLICATION_KEY_ID=test-key-id B2_APPLICATION_KEY_ID=test-key-id B2_APPLICATION_KEY=test-key "$t/.sdkharness/tests/health/golden-path" 2>&1)" ;;
  esac
  printf '%s' "$?" > "$TMP/rc"
}
if command -v go >/dev/null 2>&1; then
  mk_tree "$TMP/broken" 1.18 $'package b2\n\nfunc broken( {'
  mk_tree "$TMP/toonew" 99.0 'package b2'
  for lvl in conformance resilience health; do
    leaf_out "$TMP/broken" "$lvl"; RC="$(cat "$TMP/rc")"
    case "$out" in *"FAIL (build"*"syntax error"*) [ "$RC" = 1 ] && ok "$lvl: a checkout that does not compile is a FAIL carrying the compiler's complaint, not amber" || bad "$lvl: compile failure exited $RC, want 1";; *) bad "$lvl: compile failure not FAIL with the compiler output ($out)";; esac
    case "$out" in *"COULD-NOT-RUN"*|*"SKIP"*) bad "$lvl: compile failure still reported as amber";; *) ok "$lvl: a compile failure is never reported as COULD-NOT-RUN/SKIP";; esac
    leaf_out "$TMP/toonew" "$lvl"; RC="$(cat "$TMP/rc")"
    case "$out" in *"missing-runtime"*"older than this checkout requires"*) [ "$RC" = 0 ] && ok "$lvl: a Go older than the checkout requires is amber (missing-runtime)" || bad "$lvl: old-toolchain exited $RC, want 0";; *) bad "$lvl: old toolchain not classified as missing-runtime ($out)";; esac
  done
else
  printf '[SKIP] go: toolchain not on PATH; build classification with a real compiler not exercised\n'
fi
# A PATH with the shell tools the leaves use but no Go: amber, exit 0.
stub="$TMP/nogo"; mkdir -p "$stub"
for t in bash env mktemp awk cat cp rm dirname tr cut grep tail sed; do
  p="$(command -v "$t" 2>/dev/null)"; [ -n "$p" ] && ln -s "$p" "$stub/$t"
done
mk_tree "$TMP/nogo-tree" 1.18 'package b2'
for lvl in conformance resilience health; do
  case "$lvl" in
    conformance) out="$(env -i PATH="$stub" CONFORMANCE_TARGET=simulator CONFORMANCE_SIMULATOR_URL="$LOOP" "$TMP/nogo-tree/.sdkharness/tests/conformance/files.upload" 2>&1)" ;;
    resilience)  out="$(env -i PATH="$stub" RESILIENCE_SIMULATOR_URL="$LOOP" RESILIENCE_CONTROL_URL="$LOOP" "$TMP/nogo-tree/.sdkharness/tests/resilience/upload.retry_503" 2>&1)" ;;
    health)      out="$(env -i PATH="$stub" HEALTHCHECK_REALM_URL="$LOOP" B2_TEST_APPLICATION_KEY_ID=test-key-id B2_APPLICATION_KEY_ID=test-key-id B2_APPLICATION_KEY=test-key "$TMP/nogo-tree/.sdkharness/tests/health/golden-path" 2>&1)" ;;
  esac
  RC=$?
  case "$out" in *"missing-runtime"*"Go"*) [ "$RC" = 0 ] && ok "$lvl: no Go on PATH is COULD-NOT-RUN/SKIP (missing-runtime), exit 0" || bad "$lvl: no-go exited $RC";; *) bad "$lvl: no Go not classified as missing-runtime ($out)";; esac
done

printf 'blazer .sdkharness selftest: %d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" = 0 ]
