#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FORGE="${FORGE:-$(command -v forge || true)}"
RUN_FORK=0

usage() {
  echo "usage: ci/release-gates.sh [--fork]" >&2
}

if [[ $# -gt 1 ]]; then
  usage
  exit 2
fi
if [[ $# -eq 1 ]]; then
  if [[ "$1" != "--fork" ]]; then
    usage
    exit 2
  fi
  RUN_FORK=1
fi

if [[ -z "$FORGE" || ! -x "$FORGE" ]]; then
  echo "release gate requires Forge on PATH or in FORGE" >&2
  exit 127
fi

export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-0}"

# This is the authoritative Base-only candidate boundary. CI supplies a
# trusted merge-request baseline; an explicit BASE_V3_SCOPE_BASE is available
# for a dedicated release worktree. It intentionally requires a clean tree.
SCOPE_BASE="${BASE_V3_SCOPE_BASE:-${CI_MERGE_REQUEST_DIFF_BASE_SHA:-${CI_COMMIT_BEFORE_SHA:-}}}"
if [[ -z "$SCOPE_BASE" || "$SCOPE_BASE" =~ ^0+$ ]]; then
  echo "release gate requires BASE_V3_SCOPE_BASE or a trusted CI diff baseline" >&2
  exit 2
fi
python3 "$ROOT/ci/check_base_v3_release_scope.py" \
  --repo-root "$ROOT" --base "$SCOPE_BASE" --head "${BASE_V3_SCOPE_HEAD:-HEAD}" --require-clean

python3 "$ROOT/baseline/check_v2_abi_package.py" --strict
python3 "$ROOT/ci/check_v2_bytecode_manifest.py"
python3 "$ROOT/ci/check_generated_registries.py"
python3 "$ROOT/ci/check_loop_bounds.py"
python3 "$ROOT/ci/run_slither_gate.py"
python3 "$ROOT/pr9/website/scripts/generate_website_addresses.py" --check

(
  cd "$ROOT/v3-src"
  "$FORGE" fmt --check
)
python3 "$ROOT/ci/check_v3_reproducible_build.py"
python3 "$ROOT/ci/check_v3_runtime_sizes.py"
python3 "$ROOT/ci/check_base_v3_source_snapshot.py"

if [[ "$RUN_FORK" -eq 1 ]]; then
  if [[ -z "${BASE_RPC_URL:-}" ]]; then
    echo "fork release gate requested but protected BASE_RPC_URL is unavailable" >&2
    exit 3
  fi
  if ! find "$ROOT/v3-src/test/fork" -type f -name '*.t.sol' -print -quit 2>/dev/null | grep -q .; then
    echo "fork release gate requested but no V3 fork test suite is present" >&2
    exit 3
  fi
  (
    cd "$ROOT/v3-src"
    "$FORGE" test --match-path 'test/fork/**' --fuzz-runs "${FOUNDRY_FUZZ_RUNS:-1000}"
  )
else
  echo "fork release gate not run (optional; set RUN_FORK_TESTS=1 and provide protected BASE_RPC_URL)"
fi

npm --prefix "$ROOT/pr9/website" ci
npm --prefix "$ROOT/pr9/website" test
npm --prefix "$ROOT/pr9/website" run typecheck

git -C "$ROOT" diff --check
