#!/usr/bin/env bash
# Deploy temporary VM for all Besu containers
# This is a temporary solution before migrating to individual LXC containers

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/proxmox-api.sh" 2>/dev/null || true

# Load configuration
load_config "$PROJECT_ROOT/config/proxmox.conf"
load_config "$PROJECT_ROOT/config/network.conf" || {
    log_warn "network.conf not found, using defaults"
}

# VM Configuration
VMID="${BESU_TEMP_VMID:-9000}"
VM_NAME="besu-temp-all-nodes"
MEMORY="${BESU_TEMP_MEMORY:-32768}"  # 32GB for all nodes
CORES="${BESU_TEMP_CORES:-6}"  # Default to 6 (max allowed on some nodes)
DISK="${BESU_TEMP_DISK:-500}"  # 500GB
STORAGE="${PROXMOX_STORAGE:-local-lvm}"
IP_ADDRESS="${BESU_TEMP_IP:-192.168.11.90}"
GATEWAY="${GATEWAY:-192.168.11.1}"
NETMASK="${NETMASK:-24}"
BRIDGE="${PROXMOX_BRIDGE:-vmbr0}"

# Check for force flag
FORCE="${FORCE:-false}"

log_info "Creating temporary VM for all Besu nodes..."
log_info "VMID: $VMID, IP: $IP_ADDRESS, Memory: ${MEMORY}MB, Cores: $CORES, Disk: ${DISK}GB"

# Check if running on Proxmox host
if ! command_exists qm; then
    error_exit "This script must be run on Proxmox host (qm command not found)"
fi

check_root

# Check if VM already exists
if qm list | grep -q "^\s*$VMID\s"; then
    if [[ "$FORCE" != "true" ]]; then
        log_warn "VM $VMID already exists. Use --force to recreate."
        log_info "To force recreation: FORCE=true $0"
        exit 1
    else
        log_warn "VM $VMID exists. Stopping and removing..."
        qm stop "$VMID" 2>/dev/null || true
        sleep 2
        qm destroy "$VMID" --purge 2>/dev/null || true
        sleep 2
    fi
fi

# Create template directory if it doesn't exist
mkdir -p /var/lib/vz/template/iso

# Download Ubuntu cloud image if not exists
UBUNTU_IMAGE="ubuntu-22.04-server-cloudimg-amd64.img"
UBUNTU_IMAGE_PATH="/var/lib/vz/template/iso/$UBUNTU_IMAGE"

if [[ ! -f "$UBUNTU_IMAGE_PATH" ]]; then
    log_info "Downloading Ubuntu cloud image (this may take a few minutes)..."
    wget -q --show-progress -O "$UBUNTU_IMAGE_PATH" \
        "https://cloud-images.ubuntu.com/releases/22.04/release/$UBUNTU_IMAGE" || {
        log_error "Failed to download Ubuntu image"
        exit 1
    }
    log_success "Ubuntu image downloaded"
else
    log_info "Ubuntu image already exists, skipping download"
fi

# Create VM
log_info "Creating VM $VMID..."
qm create "$VMID" \
    --name "$VM_NAME" \
    --memory "$MEMORY" \
    --cores "$CORES" \
    --net0 virtio,bridge="$BRIDGE" \
    --scsihw virtio-scsi-pci \
    --scsi0 "$STORAGE:${DISK},format=raw" \
    --ide2 "$STORAGE:cloudinit" \
    --boot c \
    --bootdisk scsi0 \
    --serial0 socket \
    --vga serial0 \
    --agent enabled=1 \
    --ostype l26 || {
    log_error "Failed to create VM"
    exit 1
}

log_success "VM created"

# Import disk first (required before cloud-init config)
log_info "Importing Ubuntu disk (this may take a few minutes)..."
qm disk import "$VMID" "$UBUNTU_IMAGE_PATH" "$STORAGE" --format raw || {
    log_error "Failed to import disk"
    exit 1
}

# Resize disk if needed
log_info "Resizing disk to ${DISK}GB..."
qm resize "$VMID" scsi0 "+${DISK}G" || {
    log_warn "Failed to resize disk (may already be correct size)"
}

# Configure cloud-init (after disk import)
log_info "Configuring cloud-init..."
# Ensure NETMASK is in CIDR format (24, not 255.255.255.0)
if [[ "$NETMASK" == "255.255.255.0" ]]; then
    NETMASK="24"
elif [[ ! "$NETMASK" =~ ^[0-9]+$ ]]; then
    log_warn "Invalid NETMASK format: $NETMASK, using default: 24"
    NETMASK="24"
fi

# Format: ip=<ip>/<netmask>,gw=<gateway>
# Proxmox expects: ip=192.168.11.90/24,gw=192.168.11.1
IP_CONFIG="ip=${IP_ADDRESS}/${NETMASK},gw=${GATEWAY}"
log_info "Setting IP config: $IP_CONFIG"
qm set "$VMID" --ipconfig0 "$IP_CONFIG" || {
    log_error "Failed to configure IP"
    log_info "IP: $IP_ADDRESS, Netmask: $NETMASK, Gateway: $GATEWAY"
    exit 1
}
qm set "$VMID" --nameserver "8.8.8.8 8.8.4.4" || log_warn "Failed to set DNS (non-critical)"
qm set "$VMID" --ciuser root || log_warn "Failed to set cloud-init user (non-critical)"

# Try to set SSH key if available
if [[ -f ~/.ssh/id_rsa.pub ]]; then
    qm set "$VMID" --sshkeys ~/.ssh/id_rsa.pub || log_warn "Failed to set SSH key (non-critical)"
elif [[ -f ~/.ssh/id_ed25519.pub ]]; then
    qm set "$VMID" --sshkeys ~/.ssh/id_ed25519.pub || log_warn "Failed to set SSH key (non-critical)"
else
    log_warn "No SSH public key found. You'll need to set password manually."
fi

# Disk already imported above

# Start VM
log_info "Starting VM..."
qm start "$VMID" || {
    log_error "Failed to start VM"
    exit 1
}

# Wait for VM to be ready
log_info "Waiting for VM to be ready (this may take 2-3 minutes)..."
sleep 30

# Wait for SSH
max_attempts=30
attempt=0
while [ $attempt -lt $max_attempts ]; do
    if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o UserKnownHostsFile=/dev/null \
        "root@$IP_ADDRESS" "echo 'VM ready'" 2>/dev/null; then
        log_success "VM is ready!"
        break
    fi
    attempt=$((attempt + 1))
    if [ $((attempt % 5)) -eq 0 ]; then
        log_info "Still waiting for VM... ($attempt/$max_attempts)"
    fi
    sleep 10
done

if [ $attempt -eq $max_attempts ]; then
    log_error "VM did not become ready after $max_attempts attempts."
    log_info "VM is running but SSH may not be ready yet."
    log_info "Please check manually: ssh root@$IP_ADDRESS"
    log_info "You may need to set a password: qm set $VMID --cipassword 'your-password'"
    exit 1
fi

log_success "Temporary Besu VM created successfully!"
log_info "VMID: $VMID"
log_info "IP: $IP_ADDRESS"
log_info "Hostname: $VM_NAME"
log_info ""
log_info "Next steps:"
log_info "1. SSH into the VM: ssh root@$IP_ADDRESS"
log_info "2. Run setup script: cd /opt/smom-dbis-138-proxmox && ./scripts/deployment/setup-docker-besu.sh /opt/smom-dbis-138"
log_info "3. Copy docker-compose file and configs"
log_info "4. Start containers: docker compose up -d"

