#!/usr/bin/env bash
# Mint all 12 c* tokens on Chain 138 to the deployer.
# V1 tokens owned by MultiSig are minted via submitTransaction + executeTransaction.
#
# Usage: ./scripts/mint-all-c-star-138.sh [amount_human]
#   amount_human = 1000000 (default = 1M each). 6 decimals.
#   For cXAUC/cXAUT, amount_human is troy ounces (1 token = 1 troy oz Au), not USD.
# Requires: PRIVATE_KEY, RPC_URL_138 in .env.
#
# Exit: 0 all OK/skipped; 1 one or more mint failures.

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

RPC="${RPC_URL_138:-${RPC_URL:-http://192.168.11.211:8545}}"
GAS_PRICE="${GAS_PRICE_138:-1000000000}"
GAS_LIMIT_MINT="${GAS_LIMIT_MINT:-450000}"
GAS_LIMIT_MULTISIG="${GAS_LIMIT_MULTISIG:-600000}"
MULTISIG="${ADDR_MULTISIG:-0xb9E29cFa1f89d369671E640d0BB3aD94Cab43965}"
AMOUNT_HUMAN="${1:-1000000}"
BASE_UNITS=$((AMOUNT_HUMAN * 1000000))
MINT_XAU_OZ="${MINT_XAU_OZ:-50}"
XAU_BASE_UNITS=$((MINT_XAU_OZ * 1000000))

[ -n "${PRIVATE_KEY:-}" ] || { echo "PRIVATE_KEY not set"; exit 1; }
DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null) || exit 1

FAILURES=0

extract_tx_hash() {
  local out="$1"
  echo "$out" | awk '/^transactionHash[[:space:]]/ {print $2; exit}'
}

tx_status_ok() {
  local txhash="$1"
  [[ -n "$txhash" && "$txhash" == 0x* ]] || return 1
  local st
  st=$(cast receipt "$txhash" status --rpc-url "$RPC" 2>/dev/null | awk '{print $1}' || echo "")
  [[ "$st" == "1" || "$st" == "true" ]]
}

mint_via_multisig() {
  local token="$1" sym="$2" amount="$3"
  local data txhash txid
  data=$(cast calldata "mint(address,uint256)" "$DEPLOYER" "$amount")
  echo -n "  multisig mint $sym... "
  txhash=$(cast send "$MULTISIG" \
    "submitTransaction(address,uint256,bytes)" "$token" 0 "$data" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --gas-limit "$GAS_LIMIT_MULTISIG" --gas-price "$GAS_PRICE" 2>&1) || {
    echo "FAIL (submit)"
    echo "$txhash" | tail -3
    return 1
  }
  local count txid exec_out
  count=$(cast call "$MULTISIG" "getTransactionCount()(uint256)" --rpc-url "$RPC" 2>/dev/null | awk '{print $1}' || echo "0")
  if [[ "$count" =~ ^[0-9]+$ && "$count" -gt 0 ]]; then
    txid=$((count - 1))
  else
    echo "FAIL (txid)"
    return 1
  fi
  exec_out=$(cast send "$MULTISIG" "executeTransaction(uint256)" "$txid" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --gas-limit "$GAS_LIMIT_MULTISIG" --gas-price "$GAS_PRICE" 2>&1) || {
    echo "FAIL (execute)"
    echo "$exec_out" | tail -3
    return 1
  }
  txhash=$(extract_tx_hash "$exec_out")
  if tx_status_ok "$txhash"; then
    echo "OK (tx $txhash)"
    return 0
  fi
  echo "FAIL (receipt status 0: $txhash)"
  return 1
}

mint_direct() {
  local token="$1" sym="$2" amount="$3"
  local out txhash
  echo -n "  direct mint $sym... "
  out=$(cast send "$token" "mint(address,uint256)" "$DEPLOYER" "$amount" \
    --rpc-url "$RPC" --private-key "$PRIVATE_KEY" --legacy \
    --gas-limit "$GAS_LIMIT_MINT" --gas-price "$GAS_PRICE" 2>&1) || {
    echo "FAIL (send)"
    echo "$out" | tail -3
    return 1
  }
  txhash=$(extract_tx_hash "$out")
  if tx_status_ok "$txhash"; then
    echo "OK (tx $txhash)"
    return 0
  fi
  echo "FAIL (receipt status 0: $txhash)"
  return 1
}

mint_one() {
  local sym="$1" token="$2" amount="$3"
  local owner lc_dep lc_own
  owner=$(cast call "$token" "owner()(address)" --rpc-url "$RPC" 2>/dev/null || echo "")
  lc_dep=$(echo "$DEPLOYER" | tr '[:upper:]' '[:lower:]')
  lc_own=$(echo "$owner" | tr '[:upper:]' '[:lower:]')
  lc_ms=$(echo "$MULTISIG" | tr '[:upper:]' '[:lower:]')

  if [[ "$lc_own" == "$lc_dep" ]]; then
    mint_direct "$token" "$sym" "$amount" || return 1
  elif [[ "$lc_own" == "$lc_ms" ]]; then
    mint_via_multisig "$token" "$sym" "$amount" || return 1
  else
    echo "  SKIP $sym: owner=$owner (not deployer or multisig)"
    return 0
  fi
}

echo "=== Mint all c* on Chain 138 ==="
echo "  Deployer: $DEPLOYER"
echo "  MultiSig: $MULTISIG"
echo "  Amount:   $AMOUNT_HUMAN tokens each ($BASE_UNITS base)"
echo "  XAU:      $MINT_XAU_OZ troy oz each ($XAU_BASE_UNITS base)"
echo "  Gas:      mint=$GAS_LIMIT_MINT multisig=$GAS_LIMIT_MULTISIG"
echo ""

for pair in \
  "cUSDT:0x93E66202A11B1772E55407B32B44e5Cd8eda7f22" \
  "cUSDC:0xf22258f57794CC8E06237084b353Ab30fFfa640b" \
  "cEURC:0x8085961F9cF02b4d800A3c6d386D31da4B34266a" \
  "cEURT:0xdf4b71c61E5912712C1Bdd451416B9aC26949d72" \
  "cGBPC:0x003960f16D9d34F2e98d62723B6721Fb92074aD2" \
  "cGBPT:0x350f54e4D23795f86A9c03988c7135357CCaD97c" \
  "cAUDC:0xD51482e567c03899eecE3CAe8a058161FD56069D" \
  "cJPYC:0xEe269e1226a334182aace90056EE4ee5Cc8A6770" \
  "cCHFC:0x873990849DDa5117d7C644f0aF24370797C03885" \
  "cCADC:0x54dBd40cF05e15906A2C21f600937e96787f5679"; do
  sym="${pair%%:*}"
  addr="${pair#*:}"
  echo "Minting $sym..."
  mint_one "$sym" "$addr" "$BASE_UNITS" || FAILURES=$((FAILURES + 1))
done

for pair in \
  "cXAUC:0x290E52a8819A4fbD0714E517225429aA2B70EC6b" \
  "cXAUT:0x94e408E26c6FD8F4ee00b54dF19082FDA07dC96E"; do
  sym="${pair%%:*}"
  addr="${pair#*:}"
  echo "Minting $sym ($MINT_XAU_OZ oz)..."
  mint_one "$sym" "$addr" "$XAU_BASE_UNITS" || FAILURES=$((FAILURES + 1))
done

echo ""
if [[ "$FAILURES" -gt 0 ]]; then
  echo "Done with $FAILURES failure(s)."
  exit 1
fi
echo "Done — all mints succeeded."
exit 0
