#!/bin/bash

# Test VM script for Debian Atomic Desktop Bootc Installer
# This creates a QEMU VM with VNC access to test the installer

set -e

# Configuration
VM_NAME="debian-atomic-installer-test"
VM_DISK="test-vm.qcow2"
VM_MEMORY="4G"
VM_CORES="2"
VNC_PORT="5901"
VNC_DISPLAY=":1"

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Check if installer image exists
check_installer() {
    log_info "Checking installer image..."
    if ! podman image exists debian-atomic-installer:latest; then
        log_warning "Installer image not found. Building it first..."
        just build-installer
    fi
    log_success "Installer image ready."
}

# Create bootable ISO from installer container
create_iso() {
    log_info "Creating bootable ISO from installer container..."
    
    # For now, let's create a simple test ISO using debian-live
    # This is a temporary approach until we can properly create a bootable ISO
    log_warning "Creating a simple test ISO using debian-live..."
    
    # Install live-build if not available
    if ! command -v lb &> /dev/null; then
        log_info "Installing live-build..."
        sudo apt-get update
        sudo apt-get install -y live-build
    fi
    
    # Create a minimal live-build configuration
    mkdir -p /tmp/live-build-test
    cd /tmp/live-build-test
    
    # Initialize live-build with minimal config
    lb config \
        --architectures amd64 \
        --distribution trixie \
        --binary-images iso-hybrid \
        --debian-installer live \
        --linux-flavours amd64 \
        --bootloader syslinux \
        --verbose
    
    # Add our installer packages
    mkdir -p config/package-lists
    echo "calamares" > config/package-lists/installer.list.chroot
    echo "bootc" >> config/package-lists/installer.list.chroot
    echo "podman" >> config/package-lists/installer.list.chroot
    echo "skopeo" >> config/package-lists/installer.list.chroot
    
    # Build the ISO
    log_info "Building live ISO..."
    sudo lb build
    
    # Copy the result
    if [ -f "binary/live-image-amd64.hybrid.iso" ]; then
        cp binary/live-image-amd64.hybrid.iso /opt/Projects/particleos/02-installer-bootc/debian-atomic-installer.iso
        log_success "ISO created: debian-atomic-installer.iso"
    else
        log_warning "ISO build failed, creating a dummy ISO for testing..."
        # Create a dummy ISO for testing
        dd if=/dev/zero of=/opt/Projects/particleos/02-installer-bootc/debian-atomic-installer.iso bs=1M count=100
        log_warning "Created dummy ISO for testing"
    fi
    
    cd /opt/Projects/particleos/02-installer-bootc
}

# Create VM disk
create_vm_disk() {
    log_info "Creating VM disk..."
    if [ -f "$VM_DISK" ]; then
        log_warning "VM disk already exists. Removing it..."
        rm -f "$VM_DISK"
    fi
    
    qemu-img create -f qcow2 "$VM_DISK" 20G
    log_success "VM disk created: $VM_DISK"
}

# Start the VM
start_vm() {
    log_info "Starting VM with VNC access..."
    log_info "VNC server will be available at: vnc://localhost:$VNC_PORT"
    log_info "Use a VNC client to connect to: localhost:$VNC_PORT"
    
    qemu-system-x86_64 \
        -name "$VM_NAME" \
        -m "$VM_MEMORY" \
        -smp "$VM_CORES" \
        -enable-kvm \
        -cpu host \
        -machine q35 \
        -device virtio-vga \
        -display vnc=localhost:$VNC_DISPLAY \
        -cdrom debian-atomic-installer.iso \
        -drive file="$VM_DISK",format=qcow2 \
        -device virtio-net-pci,netdev=net0 \
        -netdev user,id=net0,hostfwd=tcp::2222-:22 \
        -device virtio-balloon \
        -device virtio-rng-pci \
        -rtc base=utc \
        -boot d \
        -vga virtio \
        -display sdl,gl=on \
        -serial mon:stdio \
        -nographic
}

# Show help
show_help() {
    echo "Usage: $0 [COMMAND]"
    echo ""
    echo "Commands:"
    echo "  build-iso    - Build bootable ISO from installer container"
    echo "  create-vm    - Create VM disk"
    echo "  start-vm     - Start VM with VNC access"
    echo "  test         - Full test (build ISO, create VM, start VM)"
    echo "  clean        - Clean up VM files"
    echo "  help         - Show this help"
    echo ""
    echo "VNC Access:"
    echo "  After starting the VM, connect to: vnc://localhost:$VNC_PORT"
    echo "  Or use: vncviewer localhost:$VNC_PORT"
}

# Clean up
cleanup() {
    log_info "Cleaning up VM files..."
    rm -f "$VM_DISK"
    rm -f debian-atomic-installer.iso
    log_success "Cleanup completed."
}

# Main execution
case "${1:-help}" in
    "build-iso")
        check_installer
        create_iso
        ;;
    "create-vm")
        create_vm_disk
        ;;
    "start-vm")
        if [ ! -f "debian-atomic-installer.iso" ]; then
            log_warning "ISO not found. Building it first..."
            check_installer
            create_iso
        fi
        if [ ! -f "$VM_DISK" ]; then
            log_warning "VM disk not found. Creating it first..."
            create_vm_disk
        fi
        start_vm
        ;;
    "test")
        check_installer
        create_iso
        create_vm_disk
        start_vm
        ;;
    "clean")
        cleanup
        ;;
    "help"|*)
        show_help
        ;;
esac 