#!/usr/bin/env bash
# Configure destination mappings on CCIP WETH bridges
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
load_env --file "$SCRIPT_DIR/../../.env" ${ENV_PROFILE:+--profile "$ENV_PROFILE"}
SCRIPT_NAME="ccip-configure-destination.sh"
SCRIPT_DESC="Add/update/remove destination chain mappings on CCIP WETH bridges"
SCRIPT_USAGE="${SCRIPT_NAME} --token {weth9|weth10} --action {add|update|remove} --selector <chainSelector> [--receiver <addr>] --pk <hex> [--rpc <url>] [--help]"
SCRIPT_OPTIONS="--token <name>     Bridge token type (weth9|weth10)\n--action <op>     add|update|remove\n--selector N       Destination chain selector (uint64)\n--receiver ADDR    Receiver bridge address (for add/update)\n--pk HEX           Admin private key to call bridge\n--rpc URL          RPC URL (default: ETHEREUM_MAINNET_RPC or public)\n--help             Show help"
SCRIPT_REQUIREMENTS="foundry cast, admin rights on bridge"
handle_help "${1:-}"

TOKEN=""; ACTION=""; SELECTOR=""; RECEIVER=""; PK=""; RPC_URL="${ETHEREUM_MAINNET_RPC:-https://eth.llamarpc.com}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --token) TOKEN="$2"; shift 2;;
    --action) ACTION="$2"; shift 2;;
    --selector) SELECTOR="$2"; shift 2;;
    --receiver) RECEIVER="$2"; shift 2;;
    --pk) PK="$2"; shift 2;;
    --rpc) RPC_URL="$2"; shift 2;;
    --help) handle_help "--help";;
    *) log_error "Unknown arg: $1"; exit 1;;
  esac
done

if [ -z "$TOKEN" ] || [ -z "$ACTION" ] || [ -z "$SELECTOR" ] || [ -z "$PK" ]; then
  log_error "Missing required args. See --help"
  exit 1
fi

case "$TOKEN" in
  weth9) BRIDGE_ADDR="${CCIPWETH9_BRIDGE_MAINNET:?set in .env}";;
  weth10) BRIDGE_ADDR="${CCIPWETH10_BRIDGE_MAINNET:?set in .env}";;
  *) log_error "Invalid --token: $TOKEN"; exit 1;;
esac

DRY_RUN="${DRY_RUN:-0}"
run() { if [ "$DRY_RUN" = "1" ]; then echo "[DRY RUN] $*"; else "$@"; fi }

case "$ACTION" in
  add)
    [ -n "$RECEIVER" ] || { log_error "--receiver required for add"; exit 1; }
    log_info "Adding destination: selector=$SELECTOR receiver=$RECEIVER"
    run cast send --rpc-url "$RPC_URL" --private-key "$PK" "$BRIDGE_ADDR" "addDestination(uint64,address)" "$SELECTOR" "$RECEIVER"
    ;;
  update)
    [ -n "$RECEIVER" ] || { log_error "--receiver required for update"; exit 1; }
    log_info "Updating destination: selector=$SELECTOR receiver=$RECEIVER"
    run cast send --rpc-url "$RPC_URL" --private-key "$PK" "$BRIDGE_ADDR" "updateDestination(uint64,address)" "$SELECTOR" "$RECEIVER"
    ;;
  remove)
    log_info "Removing destination: selector=$SELECTOR"
    run cast send --rpc-url "$RPC_URL" --private-key "$PK" "$BRIDGE_ADDR" "removeDestination(uint64)" "$SELECTOR"
    ;;
  *)
    log_error "Invalid --action: $ACTION"; exit 1;;
esac

log_success "Done"
