#!/usr/bin/env bash
# Fix RPC-01 (VMID 2500) configuration issues
# Usage: ./fix-rpc-2500.sh

set -e

VMID=2500

# 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"; }

# Check if running on Proxmox host
if ! command -v pct &>/dev/null; then
    log_error "This script must be run on Proxmox host (pct command not found)"
    exit 1
fi

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Fixing RPC-01 (VMID $VMID)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# 1. Check container status
log_info "1. Checking container status..."
if ! pct status $VMID &>/dev/null | grep -q "running"; then
    log_warn "   Container is not running. Starting..."
    pct start $VMID
    sleep 5
fi

# 2. Stop service
log_info ""
log_info "2. Stopping Besu RPC service..."
pct exec $VMID -- systemctl stop besu-rpc.service 2>/dev/null || true

# 3. Check which config file the service expects
log_info ""
log_info "3. Checking service configuration..."
SERVICE_FILE="/etc/systemd/system/besu-rpc.service"
CONFIG_PATH=$(pct exec $VMID -- grep "config-file" "$SERVICE_FILE" 2>/dev/null | grep -oP 'config-file=\K[^\s]+' || echo "")
log_info "   Service expects config: $CONFIG_PATH"

# Determine correct config file name
# VMID 2500 uses config-rpc-core.toml (Core RPC - local/permissioned nodes only)
if [ "$VMID" = "2500" ]; then
    CONFIG_FILE="/etc/besu/config-rpc-core.toml"
elif echo "$CONFIG_PATH" | grep -q "config-rpc-public"; then
    CONFIG_FILE="/etc/besu/config-rpc-public.toml"
elif echo "$CONFIG_PATH" | grep -q "config-rpc-core"; then
    CONFIG_FILE="/etc/besu/config-rpc-core.toml"
elif echo "$CONFIG_PATH" | grep -q "config-rpc-perm"; then
    CONFIG_FILE="/etc/besu/config-rpc-perm.toml"
else
    CONFIG_FILE="/etc/besu/config-rpc.toml"
fi

log_info "   Using config file: $CONFIG_FILE"

# 4. Create config file if missing
log_info ""
log_info "4. Ensuring config file exists..."
if ! pct exec $VMID -- test -f "$CONFIG_FILE" 2>/dev/null; then
    log_warn "   Config file missing. Creating from template..."
    
    # Try to find template
    TEMPLATE_FILE="$CONFIG_FILE.template"
    if pct exec $VMID -- test -f "$TEMPLATE_FILE" 2>/dev/null; then
        pct exec $VMID -- cp "$TEMPLATE_FILE" "$CONFIG_FILE"
        log_success "   Created from template"
    else
        log_error "   Template not found. Creating minimal config..."
        # Create minimal valid config
        pct exec $VMID -- bash -c "cat > $CONFIG_FILE <<'EOF'
data-path=\"/data/besu\"
genesis-file=\"/genesis/genesis.json\"

network-id=138
p2p-host=\"0.0.0.0\"
p2p-port=30303

miner-enabled=false
sync-mode=\"FULL\"
fast-sync-min-peers=2

# RPC Configuration (VMID 2500 - Core RPC with full APIs)
rpc-http-enabled=true
rpc-http-host=\"0.0.0.0\"
rpc-http-port=8545
rpc-http-api=[\"ETH\",\"NET\",\"WEB3\",\"ADMIN\",\"DEBUG\",\"TXPOOL\"]
rpc-http-cors-origins=[\"*\"]

rpc-ws-enabled=true
rpc-ws-host=\"0.0.0.0\"
rpc-ws-port=8546
rpc-ws-api=[\"ETH\",\"NET\",\"WEB3\",\"ADMIN\",\"DEBUG\",\"TXPOOL\"]
rpc-ws-origins=[\"*\"]

# Metrics
metrics-enabled=true
metrics-port=9545
metrics-host=\"0.0.0.0\"
metrics-push-enabled=false

logging=\"INFO\"

permissions-nodes-config-file-enabled=true
permissions-nodes-config-file=\"/permissions/permissions-nodes.toml\"
permissions-accounts-config-file-enabled=false

tx-pool-max-size=8192
tx-pool-price-bump=10
tx-pool-retention-hours=6

static-nodes-file=\"/genesis/static-nodes.json\"
# Discovery disabled for VMID 2500 (Core RPC) - only local/permissioned nodes
discovery-enabled=false
privacy-enabled=false

rpc-tx-feecap=\"0x0\"
max-peers=25
EOF"
        log_success "   Created minimal config"
    fi
    
    # Set ownership
    pct exec $VMID -- chown besu:besu "$CONFIG_FILE"
else
    log_success "   Config file exists"
fi

# 5. Remove deprecated options
log_info ""
log_info "5. Removing deprecated configuration options..."
DEPRECATED_OPTS=(
    "log-destination"
    "max-remote-initiated-connections"
    "trie-logs-enabled"
    "accounts-enabled"
    "database-path"
    "rpc-http-host-allowlist"
)

for opt in "${DEPRECATED_OPTS[@]}"; do
    if pct exec $VMID -- grep -q "^$opt" "$CONFIG_FILE" 2>/dev/null; then
        log_info "   Removing: $opt"
        pct exec $VMID -- sed -i "/^$opt/d" "$CONFIG_FILE"
    fi
done

log_success "   Deprecated options removed"

# 6. Ensure RPC is enabled
log_info ""
log_info "6. Verifying RPC is enabled..."
if ! pct exec $VMID -- grep -q "rpc-http-enabled=true" "$CONFIG_FILE" 2>/dev/null; then
    log_warn "   RPC HTTP not enabled. Enabling..."
    pct exec $VMID -- sed -i 's/rpc-http-enabled=false/rpc-http-enabled=true/' "$CONFIG_FILE" 2>/dev/null || \
    pct exec $VMID -- bash -c "echo 'rpc-http-enabled=true' >> $CONFIG_FILE"
fi

if ! pct exec $VMID -- grep -q "rpc-ws-enabled=true" "$CONFIG_FILE" 2>/dev/null; then
    log_warn "   RPC WS not enabled. Enabling..."
    pct exec $VMID -- sed -i 's/rpc-ws-enabled=false/rpc-ws-enabled=true/' "$CONFIG_FILE" 2>/dev/null || \
    pct exec $VMID -- bash -c "echo 'rpc-ws-enabled=true' >> $CONFIG_FILE"
fi

log_success "   RPC endpoints verified"

# 6b. For VMID 2500 (Core RPC), ensure discovery is disabled (local/permissioned nodes only)
if [ "$VMID" = "2500" ]; then
    log_info ""
    log_info "6b. Ensuring discovery is disabled (VMID 2500 - local/permissioned nodes only)..."
    if pct exec $VMID -- grep -q "discovery-enabled=true" "$CONFIG_FILE" 2>/dev/null; then
        log_warn "   Discovery is enabled. Disabling for strict local/permissioned node control..."
        pct exec $VMID -- sed -i 's/^discovery-enabled=true/discovery-enabled=false/' "$CONFIG_FILE"
        log_success "   Discovery disabled"
    elif ! pct exec $VMID -- grep -q "discovery-enabled" "$CONFIG_FILE" 2>/dev/null; then
        log_warn "   Discovery setting not found. Adding discovery-enabled=false..."
        pct exec $VMID -- sed -i '/^static-nodes-file/a discovery-enabled=false' "$CONFIG_FILE"
        log_success "   Discovery disabled (added)"
    else
        log_success "   Discovery is already disabled"
    fi
fi

# 7. Update service file if needed
log_info ""
log_info "7. Verifying service file configuration..."
if ! pct exec $VMID -- grep -q "config-file=$CONFIG_FILE" "$SERVICE_FILE" 2>/dev/null; then
    log_warn "   Service file references wrong config. Updating..."
    pct exec $VMID -- sed -i "s|--config-file=.*|--config-file=$CONFIG_FILE|" "$SERVICE_FILE"
    pct exec $VMID -- systemctl daemon-reload
    log_success "   Service file updated"
else
    log_success "   Service file is correct"
fi

# 8. Verify required files exist
log_info ""
log_info "8. Checking required files..."

REQUIRED_FILES=(
    "/genesis/genesis.json"
    "/genesis/static-nodes.json"
    "/permissions/permissions-nodes.toml"
)

MISSING_FILES=()
for file in "${REQUIRED_FILES[@]}"; do
    if pct exec $VMID -- test -f "$file" 2>/dev/null; then
        log_success "   Found: $file"
    else
        log_error "   Missing: $file"
        MISSING_FILES+=("$file")
    fi
done

if [ ${#MISSING_FILES[@]} -gt 0 ]; then
    log_warn "   Some required files are missing. Service may not start properly."
    log_info "   Missing files need to be copied from source project."
fi

# 9. Start service
log_info ""
log_info "9. Starting Besu RPC service..."
pct exec $VMID -- systemctl start besu-rpc.service
sleep 5

# 10. Check service status
log_info ""
log_info "10. Checking service status..."
SERVICE_STATUS=$(pct exec $VMID -- systemctl is-active besu-rpc.service 2>&1 || echo "unknown")
if [ "$SERVICE_STATUS" = "active" ]; then
    log_success "   Service is active!"
else
    log_error "   Service is not active. Status: $SERVICE_STATUS"
    log_info "   Recent logs:"
    pct exec $VMID -- journalctl -u besu-rpc.service -n 20 --no-pager 2>&1 | tail -20
fi

# 11. Test RPC endpoint
log_info ""
log_info "11. Testing RPC endpoint..."
sleep 3
RPC_TEST=$(pct exec $VMID -- timeout 5 curl -s -X POST http://localhost:8545 \
    -H "Content-Type: application/json" \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>&1 || echo "FAILED")

if echo "$RPC_TEST" | grep -q "result"; then
    BLOCK_NUM=$(echo "$RPC_TEST" | grep -oP '"result":"\K[^"]+' | head -1)
    log_success "   RPC endpoint is responding!"
    log_info "   Current block: $BLOCK_NUM"
else
    log_warn "   RPC endpoint not responding yet (may need more time to start)"
    log_info "   Response: $RPC_TEST"
fi

# Summary
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Fix Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if [ "$SERVICE_STATUS" = "active" ]; then
    log_success "✅ RPC-01 (VMID $VMID) is now running!"
    log_info ""
    log_info "Next steps:"
    log_info "1. Monitor logs: pct exec $VMID -- journalctl -u besu-rpc.service -f"
    log_info "2. Test RPC: curl -X POST http://192.168.11.250:8545 -H 'Content-Type: application/json' -d '{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\",\"params\":[],\"id\":1}'"
else
    log_error "❌ Service is still not active"
    log_info ""
    log_info "Troubleshooting:"
    log_info "1. Check logs: pct exec $VMID -- journalctl -u besu-rpc.service -n 50"
    log_info "2. Verify config: pct exec $VMID -- cat $CONFIG_FILE"
    log_info "3. Check for missing files (genesis.json, static-nodes.json, etc.)"
fi

echo ""

