#!/usr/bin/env bash
# Quick setup script for new ChainID 138 containers: 1504 (besu-sentry-5) and 2503 (besu-rpc-4)
# This script applies the Besu configuration including static-nodes.json and permissioned-nodes.json

set -euo pipefail

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

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

# Configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# New containers
declare -A NEW_CONTAINERS=(
    [1504]="besu-sentry-5"
    [2503]="besu-rpc-4"      # Ali's RPC node (0x8a)
    [2504]="besu-rpc-4"      # Ali's RPC node (0x1)
    [2505]="besu-rpc-luis"   # Luis's RPC node (0x8a)
    [2506]="besu-rpc-luis"   # Luis's RPC node (0x1)
    [2507]="besu-rpc-putu"   # Putu's RPC node (0x8a)
    [2508]="besu-rpc-putu"   # Putu's RPC node (0x1)
)

# Container IPs (update these if different)
declare -A CONTAINER_IPS=(
    [1504]="192.168.11.154"
    [2503]="192.168.11.253"  # Ali (0x8a)
    [2504]="192.168.11.254"  # Ali (0x1)
    [2505]="192.168.11.255"  # Luis (0x8a)
    [2506]="192.168.11.256"  # Luis (0x1)
    [2507]="192.168.11.257"  # Putu (0x8a)
    [2508]="192.168.11.258"  # Putu (0x1)
)

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "New ChainID 138 Containers Setup"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check if main configuration script exists
if [[ ! -f "$SCRIPT_DIR/configure-besu-chain138-nodes.sh" ]]; then
    log_error "Main configuration script not found: configure-besu-chain138-nodes.sh"
    exit 1
fi

log_info "This script will:"
log_info "1. Run the main ChainID 138 configuration for all Besu nodes"
log_info "2. Ensure new containers (1504, 2503) are properly configured"
log_info "3. Apply discovery settings (disabled for 2503)"
echo ""

# Run the main configuration script
log_info "Running main configuration script..."
if bash "$SCRIPT_DIR/configure-besu-chain138-nodes.sh"; then
    log_success "Main configuration completed"
else
    log_error "Main configuration failed"
    exit 1
fi

echo ""
log_info "=== Verifying New Containers ==="

# Verify containers are running
for vmid in "${!NEW_CONTAINERS[@]}"; do
    local hostname="${NEW_CONTAINERS[$vmid]}"
    local ip="${CONTAINER_IPS[$vmid]}"
    
    echo ""
    log_info "Verifying VMID $vmid ($hostname)..."
    
    # Check if container is running
    if ! ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
        "pct status $vmid 2>/dev/null | grep -q running"; then
        log_warn "Container $vmid is not running"
        continue
    fi
    
    log_success "Container $vmid is running"
    
    # Check if static-nodes.json exists
    if ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
        "pct exec $vmid -- test -f /var/lib/besu/static-nodes.json 2>/dev/null"; then
        log_success "  ✓ static-nodes.json exists"
    else
        log_warn "  ✗ static-nodes.json not found"
    fi
    
    # Check if permissioned-nodes.json exists
    if ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
        "pct exec $vmid -- test -f /var/lib/besu/permissions/permissioned-nodes.json 2>/dev/null"; then
        log_success "  ✓ permissioned-nodes.json exists"
    else
        log_warn "  ✗ permissioned-nodes.json not found"
    fi
    
    # For RPC node 2503, verify discovery is disabled
    if [[ "$vmid" == "2503" ]]; then
        log_info "  Checking discovery setting (should be disabled)..."
        if ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
            "pct exec $vmid -- grep -q 'discovery-enabled=false' /etc/besu/*.toml 2>/dev/null"; then
            log_success "  ✓ Discovery is disabled"
        else
            log_warn "  ✗ Discovery may not be disabled (check config files)"
        fi
    fi
    
    # Check Besu service status
    if ssh -o StrictHostKeyChecking=accept-new "root@${PROXMOX_HOST}" \
        "pct exec $vmid -- systemctl is-active --quiet besu*.service 2>/dev/null"; then
        log_success "  ✓ Besu service is running"
    else
        log_warn "  ✗ Besu service may not be running"
    fi
done

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_success "Setup Complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_info "Next steps:"
log_info "1. Verify peer connections on all nodes"
log_info "2. Check logs for any errors:"
log_info "   pct exec 1504 -- journalctl -u besu*.service -n 50"
log_info "   pct exec 2503 -- journalctl -u besu*.service -n 50"
log_info "3. Test RPC endpoint (for 2503):"
log_info "   curl -X POST http://${CONTAINER_IPS[2503]}:8545 \\"
log_info "     -H 'Content-Type: application/json' \\"
log_info "     --data '{\"jsonrpc\":\"2.0\",\"method\":\"net_peerCount\",\"params\":[],\"id\":1}'"

