#!/bin/bash
# Fix allowlist to only include addresses that have keys in Web3Signer
# Usage: ./scripts/fix-web3signer-allowlist-mismatch.sh

set -e

WEB3SIGNER_IP="192.168.11.111"

echo "═══════════════════════════════════════════════════════════════"
echo "🔧 FIXING WEB3SIGNER ALLOWLIST MISMATCH"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# Step 1: Get Web3Signer keys
echo "Step 1: Getting keys from Web3Signer..."
KEYS=$(curl -s http://$WEB3SIGNER_IP:9000/api/v1/eth1/publicKeys 2>&1 || echo "[]")

if [ "$KEYS" = "[]" ] || [ -z "$KEYS" ]; then
    echo "  ⚠️  No keys loaded in Web3Signer"
    echo "  Clearing allowlist (empty allowlist allows all addresses)"
    cd "$(dirname "$0")/.."
    ./scripts/configure-wallet-allowlist.sh ""
    echo ""
    echo "  ⚠️  Note: Empty allowlist allows ALL addresses to send transactions"
    echo "  This is NOT recommended for production. Load keys into Web3Signer first."
    exit 0
fi

KEY_COUNT=$(echo "$KEYS" | jq '. | length' 2>/dev/null || echo "0")
if [ "$KEY_COUNT" -eq 0 ]; then
    echo "  ⚠️  No keys found"
    cd "$(dirname "$0")/.."
    ./scripts/configure-wallet-allowlist.sh ""
    exit 0
fi

echo "  ✅ Found $KEY_COUNT key(s) in Web3Signer:"
echo "$KEYS" | jq -r '.[]' | while read addr; do
    echo "    - $addr"
done

# Step 2: Get current allowlist
echo ""
echo "Step 2: Checking current allowlist..."
CURRENT_ALLOWLIST=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@192.168.11.240 "grep '^WALLET_ALLOWLIST=' /opt/rpc-translator-138/.env | cut -d'=' -f2-" 2>&1 || echo "")

if [ -n "$CURRENT_ALLOWLIST" ] && [ "$CURRENT_ALLOWLIST" != "" ]; then
    echo "  Current allowlist: $CURRENT_ALLOWLIST"
    
    # Check if any addresses in allowlist don't have keys
    echo ""
    echo "  Checking for mismatches..."
    MISMATCHES=0
    echo "$CURRENT_ALLOWLIST" | tr ',' '\n' | while read addr; do
        if [ -n "$addr" ]; then
            if ! echo "$KEYS" | jq -r '.[]' | grep -qi "$(echo "$addr" | tr '[:upper:]' '[:lower:]')"; then
                echo "    ⚠️  $addr is in allowlist but has NO key in Web3Signer"
                MISMATCHES=$((MISMATCHES + 1))
            fi
        fi
    done
else
    echo "  Allowlist is empty"
fi

# Step 3: Update allowlist to only include Web3Signer keys
echo ""
echo "Step 3: Updating allowlist to match Web3Signer keys..."
WEB3SIGNER_ADDRESSES=$(echo "$KEYS" | jq -r '.[]' | tr '\n' ',' | sed 's/,$//')

if [ -n "$WEB3SIGNER_ADDRESSES" ] && [ "$WEB3SIGNER_ADDRESSES" != "" ]; then
    echo "  Setting allowlist to: $WEB3SIGNER_ADDRESSES"
    cd "$(dirname "$0")/.."
    ./scripts/configure-wallet-allowlist.sh "$WEB3SIGNER_ADDRESSES" 2>&1
    echo ""
    echo "  ✅ Allowlist updated to only include addresses with keys in Web3Signer"
else
    echo "  ⚠️  No addresses to add to allowlist"
fi

# Step 4: Verify
echo ""
echo "Step 4: Verifying configuration..."
echo "  Web3Signer keys:"
echo "$KEYS" | jq -r '.[]' | while read addr; do
    echo "    - $addr"
done

echo ""
echo "  Allowlist on translators:"
for IP in 192.168.11.240 192.168.11.241 192.168.11.242; do
    ALLOWLIST=$(ssh -i ~/.ssh/proxmox_translator -o StrictHostKeyChecking=no root@$IP "grep '^WALLET_ALLOWLIST=' /opt/rpc-translator-138/.env | cut -d'=' -f2-" 2>&1 || echo "")
    echo "    $IP: $ALLOWLIST"
done

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "✅ FIX COMPLETE"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "Note: The address 0x71e81eaec98e507f68bbcf5e2005f179db851603 has been"
echo "removed from the allowlist because it doesn't have a key in Web3Signer."
echo ""
echo "If this is a user wallet (MetaMask), this is correct - users sign"
echo "their own transactions locally, so they don't need to be in the allowlist."
echo ""
echo "If this is a service wallet, add its keystore file to Web3Signer first,"
echo "then re-run this script or add it back to the allowlist."
