#!/usr/bin/env bash
set -euo pipefail

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

source "$PROJECT_ROOT/scripts/lib/deployment/dotenv.sh"
load_deployment_env

DRY_RUN=0
AMOUNT_WEI=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    *)
      if [[ -z "$AMOUNT_WEI" ]]; then
        AMOUNT_WEI="$1"
      fi
      shift
      ;;
  esac
done

RPC_URL="${RPC_URL_MAINNET:-${ETHEREUM_MAINNET_RPC:-}}"
BRIDGE_ADDRESS="${CCIP_RELAY_BRIDGE_MAINNET:-${RELAY_BRIDGE_MAINNET:-${CW_BRIDGE_MAINNET:-}}}"
WETH_ADDRESS="${WETH9_MAINNET:-0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2}"

if [[ -z "${PRIVATE_KEY:-}" ]]; then
  echo "Set PRIVATE_KEY in .env" >&2
  exit 1
fi
if [[ -z "$RPC_URL" ]]; then
  echo "Set ETHEREUM_MAINNET_RPC (or RPC_URL_MAINNET) in .env" >&2
  exit 1
fi
if [[ -z "$BRIDGE_ADDRESS" ]]; then
  echo "Set CCIP_RELAY_BRIDGE_MAINNET (or RELAY_BRIDGE_MAINNET / CW_BRIDGE_MAINNET) in .env" >&2
  exit 1
fi

DEPLOYER="$(cast wallet address --private-key "$PRIVATE_KEY")"

if [[ -z "$AMOUNT_WEI" ]]; then
  AMOUNT_WEI="$(cast call "$WETH_ADDRESS" "balanceOf(address)(uint256)" "$DEPLOYER" --rpc-url "$RPC_URL")"
fi

AMOUNT_WEI="$(echo "$AMOUNT_WEI" | awk '{print $1}')"

if [[ -z "$AMOUNT_WEI" || "$AMOUNT_WEI" == "0" ]]; then
  if [[ "$DRY_RUN" == "1" ]]; then
    AMOUNT_WEI="1000000000000000"
    echo "No WETH available; using placeholder amount for dry-run: $AMOUNT_WEI wei"
  else
    echo "No WETH available to fund the Mainnet relay bridge." >&2
    exit 1
  fi
fi

CMD=(cast send "$WETH_ADDRESS" "transfer(address,uint256)" "$BRIDGE_ADDRESS" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "$PRIVATE_KEY" --legacy)
DRY_CMD=(cast send "$WETH_ADDRESS" "transfer(address,uint256)" "$BRIDGE_ADDRESS" "$AMOUNT_WEI" --rpc-url "$RPC_URL" --private-key "<PRIVATE_KEY>" --legacy)

echo "Mainnet relay funding"
echo "  Deployer: $DEPLOYER"
echo "  WETH:     $WETH_ADDRESS"
echo "  Bridge:   $BRIDGE_ADDRESS"
echo "  Amount:   $AMOUNT_WEI wei"

if [[ "$DRY_RUN" == "1" ]]; then
  printf '  [DRY RUN] '
  printf '%q ' "${DRY_CMD[@]}"
  printf '\n'
  exit 0
fi

"${CMD[@]}"
