#!/bin/bash
# Check RPC Configuration for Transaction Blocking Issues
# Focuses on account permissioning, gas price, and validation

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }
log_section() { echo -e "${CYAN}════════════════════════════════════════${NC}"; }

# RPC Nodes
declare -A RPC_NODES
RPC_NODES[2500]="192.168.11.250"
RPC_NODES[2501]="192.168.11.251"
RPC_NODES[2502]="192.168.11.252"
RPC_NODES[2400]="192.168.11.240"

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# Function to execute RPC call
rpc_call() {
    local ip="$1"
    local method="$2"
    local params="${3:-[]}"
    local port="${4:-8545}"
    
    curl -s -X POST "http://${ip}:${port}" \
        -H 'Content-Type: application/json' \
        -d "{\"jsonrpc\":\"2.0\",\"method\":\"${method}\",\"params\":${params},\"id\":1}" 2>/dev/null || echo "{\"error\":\"connection_failed\"}"
}

# Function to check node configuration
check_node_config() {
    local vmid="$1"
    local ip="$2"
    local hostname="$3"
    
    log_section
    log_info "Checking Configuration - ${hostname} (${ip})"
    log_section
    echo ""
    
    # 1. Check account permissioning
    log_info "1. Account Permissioning Configuration"
    PERM_FILES=$(ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" \
        "pct exec ${vmid} -- find /etc/besu -name '*permission*.toml' -o -name '*.toml' | xargs grep -l 'permissions-accounts' 2>/dev/null" 2>/dev/null || echo "")
    
    if [ -n "$PERM_FILES" ]; then
        for file in $PERM_FILES; do
            PERM_ENABLED=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
                "pct exec ${vmid} -- grep -i 'permissions-accounts-config-file-enabled' ${file} 2>/dev/null" 2>/dev/null || echo "")
            
            if echo "$PERM_ENABLED" | grep -qi "true"; then
                log_error "Account permissioning is ENABLED in ${file}"
                log_info "Config: ${PERM_ENABLED}"
                
                # Check permission file
                PERM_FILE=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
                    "pct exec ${vmid} -- grep -i 'permissions-accounts-config-file' ${file} 2>/dev/null | grep -v 'enabled' | head -1" 2>/dev/null || echo "")
                
                if [ -n "$PERM_FILE" ]; then
                    PERM_PATH=$(echo "$PERM_FILE" | grep -o '"[^"]*"' | head -1 | tr -d '"')
                    if [ -n "$PERM_PATH" ]; then
                        PERM_CONTENT=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
                            "pct exec ${vmid} -- cat ${PERM_PATH} 2>/dev/null" 2>/dev/null || echo "")
                        
                        if [ -z "$PERM_CONTENT" ] || echo "$PERM_CONTENT" | grep -q "^[[:space:]]*$"; then
                            log_warn "Permission file ${PERM_PATH} is EMPTY (all accounts should be allowed)"
                        else
                            log_warn "Permission file ${PERM_PATH} contains:"
                            echo "$PERM_CONTENT" | head -20 | sed 's/^/  /'
                        fi
                    fi
                fi
            else
                log_success "Account permissioning is DISABLED"
            fi
        done
    else
        # Check config files directly
        CONFIG_FILES=$(ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" \
            "pct exec ${vmid} -- ls /etc/besu/*.toml 2>/dev/null" 2>/dev/null || echo "")
        
        for config in $CONFIG_FILES; do
            PERM_ENABLED=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" \
                "pct exec ${vmid} -- grep -i 'permissions-accounts-config-file-enabled' ${config} 2>/dev/null" 2>/dev/null || echo "")
            
            if [ -n "$PERM_ENABLED" ]; then
                if echo "$PERM_ENABLED" | grep -qi "true"; then
                    log_error "Account permissioning is ENABLED in ${config}"
                else
                    log_success "Account permissioning is DISABLED in ${config}"
                fi
            fi
        done
    fi
    echo ""
    
    # 2. Check minimum gas price
    log_info "2. Minimum Gas Price Configuration"
    MIN_GAS_CONFIG=$(ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" \
        "pct exec ${vmid} -- grep -iE 'min-gas-price|min.*gas' /etc/besu/*.toml 2>/dev/null" 2>/dev/null || echo "")
    
    if [ -n "$MIN_GAS_CONFIG" ]; then
        log_warn "Minimum gas price configured:"
        echo "$MIN_GAS_CONFIG" | sed 's/^/  /'
        
        # Extract value
        MIN_GAS_VALUE=$(echo "$MIN_GAS_CONFIG" | grep -oE '[0-9]+' | head -1 || echo "")
        if [ -n "$MIN_GAS_VALUE" ]; then
            MIN_GAS_GWEI=$(echo "scale=2; $MIN_GAS_VALUE / 1000000000" | bc 2>/dev/null || echo "unknown")
            log_info "Minimum gas price: ${MIN_GAS_GWEI} gwei"
        fi
    else
        log_success "No minimum gas price configured (using default)"
    fi
    echo ""
    
    # 3. Get current gas price from network
    log_info "3. Current Network Gas Price"
    GAS_PRICE_HEX=$(rpc_call "$ip" "eth_gasPrice" | grep -o '"result":"[^"]*"' | cut -d'"' -f4 || echo "")
    if [ -n "$GAS_PRICE_HEX" ]; then
        GAS_PRICE_DEC=$(printf "%d" "$GAS_PRICE_HEX" 2>/dev/null || echo "0")
        GAS_PRICE_GWEI=$(echo "scale=2; $GAS_PRICE_DEC / 1000000000" | bc 2>/dev/null || echo "0")
        log_success "Current gas price: ${GAS_PRICE_GWEI} gwei (${GAS_PRICE_HEX})"
    else
        log_warn "Could not get current gas price"
    fi
    echo ""
    
    # 4. Check for recent transaction rejections in logs
    log_info "4. Recent Transaction Rejection Logs (last 30 minutes)"
    REJECTIONS=$(ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" \
        "pct exec ${vmid} -- journalctl -u besu-rpc --since '30 minutes ago' --no-pager 2>/dev/null | grep -iE 'reject|invalid|underpriced|permission|denied|not.*authorized' | tail -20" 2>/dev/null || echo "")
    
    if [ -z "$REJECTIONS" ]; then
        log_info "No recent rejection messages in logs"
    else
        log_error "Recent rejection messages found:"
        echo "$REJECTIONS" | while IFS= read -r line; do
            echo "  $line"
        done
    fi
    echo ""
    
    # 5. Get a real address from recent blocks
    log_info "5. Finding Active Addresses from Recent Blocks"
    BLOCK_HEX=$(rpc_call "$ip" "eth_blockNumber" | grep -o '"result":"[^"]*"' | cut -d'"' -f4 || echo "")
    
    if [ -n "$BLOCK_HEX" ]; then
        # Get last 10 blocks
        BLOCK_CLEAN="${BLOCK_HEX#0x}"
        BLOCK_DEC=$(printf "%d" "0x${BLOCK_CLEAN}" 2>/dev/null || echo "0")
        
        ACTIVE_ADDRESSES=""
        for i in {0..9}; do
            CHECK_BLOCK=$((BLOCK_DEC - i))
            if [ "$CHECK_BLOCK" -gt 0 ]; then
                CHECK_BLOCK_HEX=$(printf "0x%x" "$CHECK_BLOCK" 2>/dev/null || echo "")
                BLOCK_DATA=$(rpc_call "$ip" "eth_getBlockByNumber" "[\"${CHECK_BLOCK_HEX}\", true]")
                FROM_ADDR=$(echo "$BLOCK_DATA" | grep -o '"from":"0x[^"]*"' | cut -d'"' -f4 | head -1 || echo "")
                
                if [ -n "$FROM_ADDR" ] && [ "$FROM_ADDR" != "0x0000000000000000000000000000000000000000" ]; then
                    ACTIVE_ADDRESSES="${ACTIVE_ADDRESSES}${FROM_ADDR}\n"
                fi
            fi
        done
        
        if [ -n "$ACTIVE_ADDRESSES" ]; then
            UNIQUE_ADDRESSES=$(echo -e "$ACTIVE_ADDRESSES" | sort -u | head -3)
            log_success "Found active addresses:"
            echo "$UNIQUE_ADDRESSES" | while IFS= read -r addr; do
                if [ -n "$addr" ]; then
                    BALANCE_HEX=$(rpc_call "$ip" "eth_getBalance" "[\"${addr}\",\"latest\"]" | grep -o '"result":"[^"]*"' | cut -d'"' -f4 || echo "")
                    if [ -n "$BALANCE_HEX" ]; then
                        BALANCE_DEC=$(printf "%d" "$BALANCE_HEX" 2>/dev/null || echo "0")
                        BALANCE_ETH=$(echo "scale=4; $BALANCE_DEC / 1000000000000000000" | bc 2>/dev/null || echo "0")
                        echo "  ${addr}: ${BALANCE_ETH} ETH"
                    fi
                fi
            done
        else
            log_warn "No active addresses found in recent blocks"
        fi
    fi
    echo ""
    
    # 6. Test transaction format validation
    log_info "6. Testing Transaction Format Validation"
    TEST_ADDR="0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
    
    # Try with invalid format first to see error
    INVALID_TX='{"from":"'${TEST_ADDR}'","to":"'${TEST_ADDR}'","value":"0x1"}'
    INVALID_RESULT=$(rpc_call "$ip" "eth_sendTransaction" "[${INVALID_TX}]")
    INVALID_ERROR=$(echo "$INVALID_RESULT" | grep -o '"message":"[^"]*"' | cut -d'"' -f4 || echo "")
    
    if [ -n "$INVALID_ERROR" ]; then
        log_info "RPC validation error (expected): ${INVALID_ERROR}"
    fi
    echo ""
    
    echo "----------------------------------------"
    echo ""
}

# Main execution
log_section
log_info "RPC Transaction Blocking Configuration Check"
log_section
echo ""

# Check all RPC nodes
for vmid in "${!RPC_NODES[@]}"; do
    check_node_config "$vmid" "${RPC_NODES[$vmid]}" "VMID-${vmid}"
done

log_section
log_info "Configuration Check Complete"
log_section
echo ""
log_info "Common Issues Found:"
log_info "1. Account permissioning enabled - blocks unauthorized accounts"
log_info "2. Minimum gas price too high - rejects low gas transactions"
log_info "3. Transaction validation errors - format or parameter issues"
echo ""
