#!/usr/bin/env bash
# Mint cEURT to the deployer (minter); transfer fixed cXAUC/cXAUT (troy oz) to a recipient.
#
# Usage:
#   ./scripts/mint-ceurt-transfer-cxau-recipient-138.sh [cEURT_mint_human]
#   RECIPIENT=0x... XAU_OZ=500 CEURT_MINT_HUMAN=100000 ./scripts/mint-ceurt-transfer-cxau-recipient-138.sh
#   DRY_RUN=1 ./scripts/mint-ceurt-transfer-cxau-recipient-138.sh
#
# Defaults: RECIPIENT=0xCD386a74ab9E6378C8B5B44299CF595119647989, XAU_OZ=500,
#           cEURT mint = first arg or CEURT_MINT_HUMAN or 100000 (6 decimals).
#
# Requires: PRIVATE_KEY, RPC_URL_138 (or RPC_URL) in smom-dbis-138/.env or repo .env
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$PROJECT_ROOT"
[ -f .env ] && set -a && source .env && set +a
[ -f "$PROJECT_ROOT/../.env" ] && set -a && source "$PROJECT_ROOT/../.env" && set +a

RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
RECIPIENT="${RECIPIENT:-0xCD386a74ab9E6378C8B5B44299CF595119647989}"
XAU_OZ="${XAU_OZ:-500}"
CEURT_ADDR="0xdf4b71c61E5912712C1Bdd451416B9aC26949d72"
CXAUC="0x290E52a8819A4fbD0714E517225429aA2B70EC6b"
CXAUT="0x94e408E26c6FD8F4ee00b54dF19082FDA07dC96E"

CEURT_MINT_HUMAN="${1:-${CEURT_MINT_HUMAN:-100000}}"
if [ -n "${PRIVATE_KEY:-}" ]; then
  DEPLOYER="$(cast wallet address "$PRIVATE_KEY")" || exit 1
else
  DEPLOYER="(set PRIVATE_KEY)"
fi

if [ -z "${PRIVATE_KEY:-}" ] && [ -z "${DRY_RUN:-}" ]; then
  echo "PRIVATE_KEY not set (use DRY_RUN=1 to print intended commands only)"
  exit 1
fi
CEURT_BASE=$((CEURT_MINT_HUMAN * 1000000))
XAU_BASE=$((XAU_OZ * 1000000))

echo "=== Chain 138: mint cEURT + transfer cXAUC/cXAUT ==="
echo "  RPC:       $RPC"
echo "  Deployer:  $DEPLOYER"
echo "  Recipient: $RECIPIENT"
echo "  Mint cEURT to deployer: $CEURT_MINT_HUMAN ($CEURT_BASE base)"
echo "  Transfer each XAU token: $XAU_OZ troy oz ($XAU_BASE base)"
echo ""

if [ -n "${DRY_RUN:-}" ]; then
  echo "[dry-run] cast send $CEURT_ADDR mint $DEPLOYER $CEURT_BASE"
  echo "[dry-run] cast send $CXAUC transfer $RECIPIENT $XAU_BASE"
  echo "[dry-run] cast send $CXAUT transfer $RECIPIENT $XAU_BASE"
  exit 0
fi

cast send "$CEURT_ADDR" "mint(address,uint256)" "$DEPLOYER" "$CEURT_BASE" \
  --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 200000

cast send "$CXAUC" "transfer(address,uint256)" "$RECIPIENT" "$XAU_BASE" \
  --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 200000

cast send "$CXAUT" "transfer(address,uint256)" "$RECIPIENT" "$XAU_BASE" \
  --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy --gas-limit 200000

echo "Done."
