#!/usr/bin/env bash
# Optional, non-broadcasting EVM fork gates. All URLs are optional unless
# REQUIRE_FORK_RPCS=1 is explicitly set by a protected CI job.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
FORGE="${FORGE:-$HOME/.foundry/bin/forge}"
V3="$ROOT/v3-src"

test -x "$FORGE"

required_rpcs=(BASE_RPC_URL AVAX_RPC_URL ARB_RPC_URL POLYGON_RPC_URL)
if [[ "${REQUIRE_FORK_RPCS:-0}" == "1" ]]; then
  for rpc_name in "${required_rpcs[@]}"; do
    if [[ -z "${!rpc_name:-}" ]]; then
      echo "ERROR: $rpc_name is required when REQUIRE_FORK_RPCS=1" >&2
      exit 1
    fi
  done
fi

(
  cd "$V3"
  "$FORGE" build

  # This is the RPC-free suite. Fork tests are deliberately excluded so a
  # developer cannot accidentally contact a chain during normal local testing.
  "$FORGE" test --no-match-path 'test/fork/**'

  # One read-only availability test per configured supported chain. Missing
  # credentials are a documented pass/skip, including in local development.
  "$FORGE" test --match-contract SupportedChainForkAvailabilityV3Test -vv

  # The deployment/rollback simulation is Base-only by contract design.
  if [[ -n "${BASE_RPC_URL:-}" ]]; then
    "$FORGE" test --match-contract BasePilotDeploymentRollbackV3ForkTest -vv
  else
    echo "SKIP Base V3 deployment/rollback simulation: BASE_RPC_URL is not configured"
  fi
)
