#!/usr/bin/env bash
# Run G2/G3 (Trustless + Lockbox) on the chains that previously failed: BSC, POLYGON, BASE, OPTIMISM, CRONOS.
# Fixes nonce for Cronos by clearing broadcast cache first; uses --slow and delay between chains to avoid 429/nonce issues.
# Tags: --delay <sec>, --lockbox / --no-lockbox.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$REPO_ROOT"

source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
source "$SCRIPT_DIR/../lib/deployment/prompts.sh"
load_deployment_env
parse_delay_tag "$@"
parse_lockbox_tag "${PARSE_DELAY_REMAINING[@]}"

TRUSTLESS_SCRIPT="script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge"
DELAY_BETWEEN_CHAINS="${DELAY_BETWEEN_CHAINS:-45}"

echo "=============================================="
echo "G2/G3 remaining: BSC, POLYGON, BASE, OPTIMISM, CRONOS (nonce fix for Cronos)"
echo "=============================================="

# Cronos: clear nonce cache then deploy
echo ""
echo "--- Fix nonce for Cronos (clear cache) ---"
./scripts/deployment/fix-nonce-and-retry.sh --chain cronos --script "$TRUSTLESS_SCRIPT" || true
echo ""
echo "--- Deploy Trustless + Lockbox on CRONOS (chain 25) ---"
rpc="${CRONOS_RPC_URL:-https://evm.cronos.org}"
weth="0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23"
TRUSTLESS_WETH_ADDRESS="$weth" TRUSTLESS_DEPLOY_LOCKBOX="${TRUSTLESS_DEPLOY_LOCKBOX:-1}" \
  forge script script/bridge/trustless/DeployTrustlessBridge.s.sol:DeployTrustlessBridge \
  --rpc-url "$rpc" --chain-id 25 --broadcast --private-key "$PRIVATE_KEY" --slow -vvv || true
sleep "$DELAY_BETWEEN_CHAINS"

# BSC, Polygon, Base, Optimism with delay between each
for name in BSC POLYGON BASE OPTIMISM; do
  echo ""
  echo "--- Deploy Trustless + Lockbox on $name ---"
  if [[ "${TRUSTLESS_DEPLOY_LOCKBOX:-1}" == "1" ]]; then
    ./scripts/deployment/deploy-trustless-l2s.sh --chain "$name" --lockbox || true
  else
    ./scripts/deployment/deploy-trustless-l2s.sh --chain "$name" --no-lockbox || true
  fi
  sleep "$DELAY_BETWEEN_CHAINS"
done

echo ""
echo "Done. Update .env with BondManager, ChallengeManager, LiquidityPool, Inbox, Lockbox per chain."
