#!/usr/bin/env bash
# Deploy CCIPLogger to all configured chains (mainnet, BSC, Polygon, Gnosis, Cronos) via Hardhat.
# Requires: from smom-dbis-138 run `pnpm install` or `npm install` so Hardhat resolves locally; .env with PRIVATE_KEY and per-chain RPC.
# Usage: cd smom-dbis-138 && ./scripts/deployment/deploy-ccip-logger-all-chains.sh
#        CHAINS="mainnet bsc" ./scripts/deployment/deploy-ccip-logger-all-chains.sh  # only mainnet and bsc

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_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

CHAINS="${CHAINS:-mainnet bsc polygon gnosis cronos}"

if ! command -v npx &>/dev/null; then
  echo "npx not found. Install Node/npm and run: npm install" >&2
  exit 1
fi

echo "Deploying CCIPLogger to: $CHAINS"
for net in $CHAINS; do
  echo ""
  echo "=== $net ==="
  case "$net" in
    mainnet) npm run deploy:logger:mainnet 2>&1 || echo "  Failed (non-fatal)" ;;
    bsc)     NETWORK=bsc npx hardhat run scripts/ccip-deployment/deploy-ccip-logger-multichain.js --network bsc 2>&1 || echo "  Failed (non-fatal)" ;;
    polygon) npm run deploy:logger:polygon 2>&1 || echo "  Failed (non-fatal)" ;;
    gnosis)  npm run deploy:logger:gnosis 2>&1 || echo "  Failed (non-fatal)" ;;
    cronos)  npm run deploy:logger:cronos 2>&1 || echo "  Failed (non-fatal)" ;;
    *)       echo "  Unknown network: $net" ;;
  esac
done

echo ""
echo "Done. Update .env with CCIP_LOGGER_* addresses per chain if deployed."
