#!/bin/bash
#
# KVM Pre-installation Preparation
#
# Validates system readiness for KVM installation

set -euo pipefail

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

log_info() {
    echo -e "${GREEN}[KVM PREPARE]${NC} $*"
}

log_error() {
    echo -e "${RED}[KVM PREPARE ERROR]${NC} $*" >&2
}

log_warn() {
    echo -e "${YELLOW}[KVM PREPARE WARN]${NC} $*"
}

# Check for required capabilities
check_requirements() {
    local failed=0

    log_info "Checking system requirements..."

    # Check root
    if [ "$EUID" -ne 0 ]; then
        log_error "Must run as root"
        return 1
    fi

    # Check Linux kernel
    if [ ! -f /proc/cpuinfo ]; then
        log_error "Not running on Linux"
        return 1
    fi

    log_info "✓ Running as root on Linux"

    # Check CPU virtualization support
    if ! grep -q -E "vmx|svm" /proc/cpuinfo; then
        log_error "CPU does not support virtualization (no vmx/svm flag)"
        return 1
    fi
    log_info "✓ CPU supports virtualization"

    # Check if virtualization is enabled in BIOS (if not in nested virt)
    if ! grep -q "^flags.*hypervisor" /proc/cpuinfo; then
        # Check /proc/sys/kernel/kvm_* files
        if [ ! -d /sys/module/kvm ]; then
            log_warn "KVM kernel module not loaded - will be loaded during installation"
        fi
    else
        log_info "✓ Running in nested virtualization environment"
    fi

    # Check disk space
    available_space=$(df /var/lib | awk 'NR==2 {print $4}')
    if [ "$available_space" -lt 102400 ]; then  # 100MB in KB
        log_error "/var/lib has insufficient space (need 100MB)"
        return 1
    fi
    log_info "✓ Sufficient disk space available"

    # Check memory
    available_memory=$(free -m | awk 'NR==2 {print $2}')
    if [ "$available_memory" -lt 2048 ]; then
        log_error "Insufficient memory (need 2GB, have ${available_memory}MB)"
        return 1
    fi
    log_info "✓ Sufficient memory available"

    return 0
}

# Prepare system
prepare_system() {
    log_info "Preparing system for KVM..."

    # Create libvirt directories if needed
    mkdir -p /var/lib/libvirt/qemu || true
    mkdir -p /var/lib/libvirt/images || true

    log_info "✓ KVM directories prepared"
    return 0
}

# Main
check_requirements && prepare_system

exit $?
