#!/usr/bin/env bash
# Check bash syntax of deployment scripts and lib (bash -n). Run from anywhere.
# Usage: ./scripts/deployment/check-syntax.sh   or   bash scripts/deployment/check-syntax.sh
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$REPO_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

FAIL=0

check() {
  if bash -n "$1" 2>/dev/null; then
    echo "  OK   $1"
  else
    echo "  FAIL $1"
    FAIL=1
  fi
}

echo "Checking deployment scripts and lib..."
check scripts/lib/deployment/prompts.sh
check scripts/lib/deployment/dotenv.sh
check scripts/deployment/fund-mainnet-lp.sh
check scripts/deployment/run-all-four-gaps.sh
check scripts/deployment/deploy-pmm-all-l2s.sh
check scripts/deployment/deploy-trustless-l2s.sh
check scripts/deployment/fund-ccip-bridges-with-link.sh
check scripts/deployment/fix-nonce-and-retry.sh
check scripts/deployment/run-remaining-g2g3-with-nonce-fix.sh
check scripts/deployment/run-pmm-and-pools.sh
check scripts/deployment/check-balances-gas-and-deploy.sh

if [[ "$FAIL" -eq 0 ]]; then
  echo "All passed."
else
  echo "Some checks failed."
  exit 1
fi
