#!/usr/bin/env bash
#
# Gate: the tree run-scenario.sh is about to boot must be a TEST_HARNESS
# build -- the probe endpoint and codec fault sites compile out entirely
# otherwise (plan-testkit-integration.md Ground truth: without both
# TEST_HARNESS=1 and -DNGX_TEST_HARNESS, the module builds and answers, but
# every fault-injection oracle here would pass by testing nothing).
#
# Checked the same way run-scenario.sh/lib.sh resolve the build tree, so this
# gate can never SKIP a tree the engine would boot fine or pass one it would
# reject -- see consumer-zstd/requires's identical reasoning for why the
# derivation must match lib.sh exactly.
set -euo pipefail

FLAVOR="${2:-nginx}"
VERSION="${3:-1.31.3}"
BUILD="${PROBER_BUILD:-${PROBER_ROOT:-$(cd ../.. && pwd)}/.build/${FLAVOR}-${VERSION}}"
SO="$BUILD/objs/ngx_http_zstd_filter_module.so"

if [ ! -f "$SO" ]; then
    echo "ngx_http_zstd_filter_module.so not found at $SO -- build it first"
    exit 1
fi

PROBE_SYMBOLS="$(nm "$SO" 2>/dev/null | grep -c ' ngx_test_probe_' || true)"
if [ "$PROBE_SYMBOLS" -eq 0 ]; then
    echo "$SO carries no ngx_test_probe_* symbols -- this is a packaged (non-harness) build; configure with TEST_HARNESS=1 CFLAGS=\"\$CFLAGS -DNGX_TEST_HARNESS\" first (see plan-testkit-integration.md Ground truth)"
    exit 1
fi

# Oracle 4 decodes the response and compares it against the origin file, so a
# missing decoder would silently weaken it to "200 and nonempty". Fail here
# instead: a gate that cannot run its assertion is not a gate.
if ! command -v zstd >/dev/null 2>&1; then
    echo "zstd(1) not found -- oracle 4 decodes the CODEC_END ZERO response and compares it byte-for-byte with the origin file"
    exit 1
fi

# The refPrefix fault arm negotiates a real dcz response. It derives the
# Available-Dictionary value from the checked-in fixture, so the CLI used for
# that derivation is part of the oracle rather than an optional convenience.
if ! command -v openssl >/dev/null 2>&1; then
    echo "openssl(1) not found -- the refPrefix arm derives the dcz negotiation hash with openssl dgst/base64"
    exit 1
fi

# zstd_dcz_dict_file opens the dictionary during nginx -t, before driver.sh
# runs. Stage the canonical dcz fixture here, the same pre-config hook used by
# codec-call-count, and reference it from nginx.conf through @BUILD_OBJS@.
DICT_SRC="$(cd "$(dirname "$0")/../../suite" && pwd)/dcz-dict"
if [ ! -f "$DICT_SRC" ]; then
    echo "dictionary fixture not found at $DICT_SRC"
    exit 1
fi
if ! cp -f "$DICT_SRC" "$BUILD/objs/fault-arms.dict"; then
    echo "cannot stage the dictionary fixture into $BUILD/objs"
    exit 1
fi

exit 0
