#!/bin/sh
set -eu

ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
# shellcheck disable=SC1091
. "$ROOT/rehearsal-versions.env"

case "$LOCAL_RPC_URL" in
  http://127.0.0.1:*|http://localhost:*) ;;
  *) echo "Refusing non-local RPC URL: $LOCAL_RPC_URL" >&2; exit 1 ;;
esac

LEDGER=$(mktemp -d "${TMPDIR:-/tmp}/vaultfire-solana-ledger.XXXXXX")
HOME_DIR=$(mktemp -d "${TMPDIR:-/tmp}/vaultfire-solana-home.XXXXXX")
LOG="$LEDGER/validator.log"
PID=""
cleanup() {
  if [ -n "$PID" ]; then kill "$PID" 2>/dev/null || true; wait "$PID" 2>/dev/null || true; fi
  rm -rf "$LEDGER" "$HOME_DIR"
}
trap cleanup EXIT HUP INT TERM

set -- solana-test-validator \
  --reset \
  --ledger "$LEDGER" \
  --rpc-port 8899 \
  --faucet-port 9900 \
  --bind-address 127.0.0.1 \
  --gossip-host 127.0.0.1 \
  --dynamic-port-range 10000-10100 \
  --quiet

node "$ROOT/scripts/verify-release-scope.mjs" --require-committed-candidate
# Program names are restricted by the canonical manifest to lowercase ASCII
# identifiers, so shell word iteration is safe here and preserves "$@".
set -- solana-test-validator \
  --reset \
  --ledger "$LEDGER" \
  --rpc-port 8899 \
  --faucet-port 9900 \
  --bind-address 127.0.0.1 \
  --gossip-host 127.0.0.1 \
  --dynamic-port-range 10000-10100 \
  --quiet
for name in $(node "$ROOT/scripts/list-supported-programs.mjs"); do
  program_id=$(node --input-type=module -e \
    "import { readManifest, programByName } from './scripts/release-policy.mjs'; console.log(programByName(readManifest(), process.argv[1]).programId)" \
    "$name")
  test -n "$program_id"
  artifact="$ROOT/artifacts/sbf/$name.so"
  test -s "$artifact"
  set -- "$@" --bpf-program "$program_id" "$artifact"
done

HOME="$HOME_DIR" "$@" >"$LOG" 2>&1 &
PID=$!

i=0
until solana cluster-version --url "$LOCAL_RPC_URL" >/dev/null 2>&1; do
  i=$((i + 1))
  if [ "$i" -gt 60 ]; then cat "$LOG" >&2; echo "local validator did not become ready" >&2; exit 1; fi
  sleep 1
done

node "$ROOT/scripts/verify-local-validator.mjs"
printf 'Local-only disabled-upgrade preload rehearsal passed for the 6 supported candidates.\n'
