#!/usr/bin/env bash
# Deploy event-only CCIPRouter + outbound WMON bridge on Monad for Monad→138 relay lane.
#
# Usage: ./scripts/deployment/deploy-monad-outbound-138-lane.sh --execute

set -euo pipefail

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

# shellcheck disable=SC1090
source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
load_deployment_env --repo-root "$PROJECT_ROOT"

EXECUTE=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --execute) EXECUTE=1; shift ;;
    --dry-run) echo "[DRY RUN] forge DeployMonad138OutboundLane"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 1 ;;
  esac
done

[[ "$EXECUTE" == "1" ]] || { echo "Pass --execute"; exit 0; }
require_private_key_env || exit 1
"$SCRIPT_DIR/preflight-monad-deploy.sh"

RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
export WETH9_MONAD="${WETH9_MONAD:-0x754704bc059f8c67012fed69bc8a327a5aafb603}"
export CCIP_FEE_TOKEN="0x0000000000000000000000000000000000000000"
export CHAIN138_SELECTOR="${CHAIN138_SELECTOR:-}"

LOG="/tmp/monad-outbound-138-lane.log"
forge script script/DeployMonad138OutboundLane.s.sol:DeployMonad138OutboundLane \
  --rpc-url "$RPC" --chain-id 143 --private-key "$PRIVATE_KEY" \
  --broadcast --legacy -vvv 2>&1 | tee "$LOG"

ROUTER=$(grep -oE "Monad event-only CCIPRouter: 0x[a-fA-F0-9]{40}" "$LOG" | grep -oE "0x[a-fA-F0-9]{40}" | tail -1)
BRIDGE=$(grep -oE "Monad outbound CCIPWETH9Bridge: 0x[a-fA-F0-9]{40}" "$LOG" | grep -oE "0x[a-fA-F0-9]{40}" | tail -1)
echo "CCIP_ROUTER_MONAD_SEND=$ROUTER"
echo "CCIPWETH9_BRIDGE_MONAD_SEND=$BRIDGE"
