#!/usr/bin/env bash
# Configure CCIPWETH9Bridge destinations

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Load environment
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
fi

MAINNET_RPC="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
CHAIN138_RPC="${RPC_URL:-https://rpc.d-bis.org}"
PRIVATE_KEY="${PRIVATE_KEY}"
if [[ ! "$PRIVATE_KEY" =~ ^0x ]]; then
    PRIVATE_KEY="0x$PRIVATE_KEY"
fi

WETH9_BRIDGE_MAINNET=$(grep "CCIPWETH9_BRIDGE_MAINNET=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")
WETH9_BRIDGE_CHAIN138=$(grep "CCIPWETH9_BRIDGE_CHAIN138=" "$PROJECT_ROOT/.env" 2>/dev/null | cut -d'=' -f2 | tr -d ' "' || echo "")

CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-0x000000000000008a}"
ETH_SELECTOR="${ETH_MAINNET_SELECTOR:-0x500147}"

if [ -z "$WETH9_BRIDGE_MAINNET" ] || [ -z "$WETH9_BRIDGE_CHAIN138" ]; then
    echo "Error: Bridge addresses not found in .env"
    exit 1
fi

echo "Configuring CCIPWETH9Bridge..."
echo "  Mainnet Bridge: $WETH9_BRIDGE_MAINNET"
echo "  Chain-138 Bridge: $WETH9_BRIDGE_CHAIN138"
echo "To configure, run:"
echo "  # On Mainnet:"
echo "  cast send $WETH9_BRIDGE_MAINNET \"addDestination(uint64,address)\" $CHAIN138_SELECTOR $WETH9_BRIDGE_CHAIN138 --rpc-url $MAINNET_RPC --private-key $PRIVATE_KEY"
echo "  # On Chain-138:"
echo "  cast send $WETH9_BRIDGE_CHAIN138 \"addDestination(uint64,address)\" $ETH_SELECTOR $WETH9_BRIDGE_MAINNET --rpc-url $CHAIN138_RPC --private-key $PRIVATE_KEY"
