#!/bin/bash
# Configure wallet allowlist on all translator VMIDs
# Usage: ./scripts/configure-wallet-allowlist.sh [address1,address2,...]
# Example: ./scripts/configure-wallet-allowlist.sh "0x1234...,0xabcd..."

set -e

ALLOWLIST="${1:-}"

if [ -z "$ALLOWLIST" ]; then
    echo "═══════════════════════════════════════════════════════════════"
    echo "🔒 WALLET ALLOWLIST CONFIGURATION"
    echo "═══════════════════════════════════════════════════════════════"
    echo ""
    echo "Usage: $0 <address1,address2,...>"
    echo ""
    echo "Examples:"
    echo "  # Single address"
    echo "  $0 0x1234567890123456789012345678901234567890"
    echo ""
    echo "  # Multiple addresses"
    echo "  $0 \"0x1234...,0xabcd...,0x5678...\""
    echo ""
    echo "  # Empty (allow all - NOT recommended for production)"
    echo "  $0 \"\""
    echo ""
    echo "Current configuration:"
    for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
        echo ""
        echo "VMID $IP:"
        ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "grep WALLET_ALLOWLIST /opt/rpc-translator-138/.env 2>/dev/null || echo '  Not set'" 2>&1
    done
    exit 0
fi

echo "═══════════════════════════════════════════════════════════════"
echo "🔒 CONFIGURING WALLET ALLOWLIST"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Allowlist: $ALLOWLIST"
echo ""

if [ -z "$ALLOWLIST" ]; then
    echo "⚠️  WARNING: Empty allowlist allows ALL addresses!"
    echo "   This is NOT recommended for production."
    read -p "Continue? (yes/no): " confirm
    if [ "$confirm" != "yes" ]; then
        echo "Aborted."
        exit 1
    fi
fi

# Configure on all VMIDs
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    echo "Configuring VMID $IP..."
    
    # Update .env file
    ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP bash <<ENVUPDATE
cd /opt/rpc-translator-138
if grep -q "^WALLET_ALLOWLIST=" .env; then
    sed -i "s|^WALLET_ALLOWLIST=.*|WALLET_ALLOWLIST=$ALLOWLIST|" .env
else
    echo "WALLET_ALLOWLIST=$ALLOWLIST" >> .env
fi
echo "✅ Updated .env file"
ENVUPDATE
    
    # Restart service
    echo "  Restarting service..."
    ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "systemctl restart rpc-translator-138.service && sleep 2 && systemctl is-active rpc-translator-138.service" 2>&1 | tail -1
    
    echo ""
done

echo "═══════════════════════════════════════════════════════════════"
echo "✅ WALLET ALLOWLIST CONFIGURED"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Allowlist has been configured on all translator VMIDs."
echo ""
echo "To verify, check the logs:"
echo "  ssh -i ~/.ssh/proxmox_translator root@192.168.11.240 'journalctl -u rpc-translator-138.service -n 20 | grep -i allowlist'"
