#!/usr/bin/env bash
# Enable ADMIN RPC methods on Besu RPC node via SSH
# This enables admin_removeTransaction and other admin methods
# Usage: ./enable-admin-rpc-ssh.sh [vmid] [rpc_ip]

set -euo pipefail

VMID="${1:-2500}"
RPC_IP="${2:-192.168.11.250}"
RPC_CONFIG="/etc/besu/config-rpc.toml"
PROXMOX_HOST="192.168.11.10"
PROXMOX_PASS="L@kers2010"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

log_info "========================================="
log_info "Enable ADMIN on Besu RPC Node (via SSH)"
log_info "========================================="
log_info ""

# Check if sshpass is available
if ! command -v sshpass >/dev/null 2>&1; then
    log_error "sshpass is required"
    exit 1
fi

# Test SSH connection
log_info "Testing SSH connection..."
if ! sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 \
    "root@$PROXMOX_HOST" "echo 'OK'" 2>/dev/null; then
    log_error "Cannot connect to Proxmox host"
    exit 1
fi

# Check current config
log_info "Checking current RPC API configuration..."
CURRENT_API=$(sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- grep -E '^rpc-http-api=' $RPC_CONFIG 2>/dev/null || echo ''" 2>/dev/null || echo "")

if [ -n "$CURRENT_API" ]; then
    log_info "Current: $CURRENT_API"
    if echo "$CURRENT_API" | grep -qi "ADMIN"; then
        log_success "✓ ADMIN already enabled"
        exit 0
    fi
fi

# Backup and update config
log_info "Backing up config..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- cp $RPC_CONFIG ${RPC_CONFIG}.backup.\$(date +%Y%m%d_%H%M%S)" 2>/dev/null || true

# Update to include ADMIN
log_info "Updating config to enable ADMIN..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- sed -i '/^rpc-http-api=/d' $RPC_CONFIG" 2>/dev/null || true

sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- sed -i '/^rpc-http-port=/a rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"TXPOOL\",\"ADMIN\"]' $RPC_CONFIG" 2>/dev/null || {
    log_error "Failed to update config"
    exit 1
}

log_success "✓ Config updated"

# Restart service
log_info "Restarting Besu RPC service..."
sshpass -p "$PROXMOX_PASS" ssh -o StrictHostKeyChecking=no \
    "root@$PROXMOX_HOST" "pct exec $VMID -- systemctl restart besu-rpc" 2>/dev/null || {
    log_error "Failed to restart service"
    exit 1
}

log_success "✓ Service restarted"

# Wait and verify
log_info "Waiting for RPC to come online..."
sleep 10

RPC_URL="http://${RPC_IP}:8545"
for i in {1..10}; do
    RPC_MODULES=$(curl -s -X POST -H "Content-Type: application/json" \
        --data '{"jsonrpc":"2.0","method":"rpc_modules","params":[],"id":1}' \
        "$RPC_URL" 2>/dev/null || echo "")
    
    if [ -n "$RPC_MODULES" ] && echo "$RPC_MODULES" | jq -e '.result' >/dev/null 2>&1; then
        if echo "$RPC_MODULES" | jq -r '.result | keys[]' 2>/dev/null | grep -qi "admin"; then
            log_success "✓ ADMIN is now enabled"
            exit 0
        else
            log_warn "⚠ RPC online but ADMIN not found (attempt $i/10)"
            sleep 2
        fi
    else
        sleep 2
    fi
done

log_warn "⚠ Could not verify ADMIN is enabled"

