#!/usr/bin/env bash
# Mint cW* tokens on a given chain to the deployer. Deployer has MINTER_ROLE on CompliantWrappedToken.
# Usage: ./scripts/mint-cw-on-chain.sh <CHAIN_NAME> [amount_human]
#   CHAIN_NAME = Mainnet | Cronos | BSC | Polygon | Gnosis | Avalanche | Base | Arbitrum | Optimism
#   amount_human = tokens in human units (default 1000000 = 1M). 6 decimals.
# Requires: PRIVATE_KEY, <CHAIN>_RPC, CWUSDT_<CHAIN>, CWUSDC_<CHAIN>, etc. in .env.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
if [[ -f "$SCRIPT_DIR/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [[ -f .env ]]; then
  set -a
  source .env
  set +a
  if [[ -z "${PRIVATE_KEY:-}" && -n "${DEPLOYER_PRIVATE_KEY:-}" ]]; then
    export PRIVATE_KEY="$DEPLOYER_PRIVATE_KEY"
  fi
fi

CHAIN_NAME="${1:-}"
AMOUNT_HUMAN="${2:-1000000}"
BASE_UNITS=$((AMOUNT_HUMAN * 10**6))

[[ -n "$CHAIN_NAME" ]] || { echo "Usage: $0 <CHAIN_NAME> [amount_human]. CHAIN_NAME=Mainnet|Cronos|BSC|Polygon|Gnosis|Avalanche|Base|Arbitrum|Optimism"; exit 1; }
[[ -n "${PRIVATE_KEY:-}" ]] || { echo "PRIVATE_KEY not set"; exit 1; }
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null) || exit 1

CHAIN_UPPER=$(echo "$CHAIN_NAME" | tr '[:lower:]' '[:upper:]')

get_rpc() {
  case "$CHAIN_UPPER" in
    MAINNET)   echo "${ETHEREUM_MAINNET_RPC:-${ETH_MAINNET_RPC_URL:-}}";;
    CRONOS)    echo "${CRONOS_RPC_URL:-${CRONOS_RPC:-}}";;
    BSC)       echo "${BSC_RPC_URL:-${BSC_RPC:-}}";;
    POLYGON)   echo "${POLYGON_MAINNET_RPC:-${POLYGON_RPC_URL:-}}";;
    GNOSIS)    echo "${GNOSIS_RPC:-${GNOSIS_MAINNET_RPC:-}}";;
    AVALANCHE) echo "${AVALANCHE_RPC_URL:-${AVALANCHE_RPC:-}}";;
    BASE)      echo "${BASE_MAINNET_RPC:-${BASE_RPC_URL:-}}";;
    ARBITRUM)  echo "${ARBITRUM_MAINNET_RPC:-${ARBITRUM_RPC:-}}";;
    OPTIMISM)  echo "${OPTIMISM_MAINNET_RPC:-${OPTIMISM_RPC:-}}";;
    *) echo "";;
  esac
}

RPC=$(get_rpc)
[[ -n "$RPC" ]] || { echo "No RPC for $CHAIN_NAME. Set e.g. POLYGON_MAINNET_RPC in .env"; exit 1; }

# cW* env vars: CWUSDT_POLYGON, CWUSDC_POLYGON, ...
for var in CWUSDT CWUSDC CWEURC CWEURT CWGBPC CWGBPT CWAUDC CWJPYC CWCHFC CWCADC CWXAUC CWXAUT; do
  addr_var="${var}_${CHAIN_UPPER}"
  addr="${!addr_var:-}"
  [[ -n "$addr" ]] || continue
  echo -n "Minting ${var}... "
  if cast send "$addr" "mint(address,uint256)" "$DEPLOYER" "$BASE_UNITS" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 100000 2>/dev/null; then
    echo "OK"
  else
    echo "FAIL"
  fi
done
echo "Done. Ensure CWUSDT_${CHAIN_UPPER}, CWUSDC_${CHAIN_UPPER}, etc. are in .env (from DeployCWTokens output)."
