#!/bin/bash
# Phase 5 Startup Script - Particle OS Integration Testing
# Location: /home/joe/bootc-image-builder/debian-bootc-image-builder/scripts/phase5-start.sh

set -e

echo "======================================="
echo "PHASE 5: PARTICLE OS INTEGRATION"
echo "Real Image Testing and Desktop Integration"
echo "======================================="

# Set working directory
WORK_DIR="/home/joe/bootc-image-builder/debian-bootc-image-builder"
cd "$WORK_DIR"

echo "Working directory: $WORK_DIR"
echo ""

# Function to check if command exists
check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo "ERROR: $1 is not installed or not in PATH"
        exit 1
    fi
}

# Check prerequisites
echo "Checking prerequisites..."
check_command podman
check_command python3
check_command pytest
echo "✅ All prerequisites found"
echo ""

# Create output directory
echo "Setting up output directory..."
mkdir -p output
echo "✅ Output directory ready: $WORK_DIR/output"
echo ""

# Function to build container image
build_image() {
    local containerfile="$1"
    local tag="$2"
    local description="$3"
    
    echo "Building $description..."
    echo "Containerfile: $containerfile"
    echo "Tag: $tag"
    
    if podman build -f "$containerfile" -t "$tag" .; then
        echo "✅ Successfully built $tag"
        
        # Show image info
        echo "Image details:"
        podman images "$tag" --format "table {{.Repository}}:{{.Tag}}  {{.Size}}  {{.Created}}"
        echo ""
        return 0
    else
        echo "❌ Failed to build $tag"
        return 1
    fi
}

# Function to generate bootable image
generate_bootable_image() {
    local container_tag="$1"
    local output_name="$2"
    local description="$3"
    
    echo "Generating bootable $description..."
    echo "Container: $container_tag"
    echo "Output: $output_name"
    
    if podman run --rm --privileged \
        -v "$WORK_DIR/output:/output" \
        quay.io/centos-bootc/bootc-image-builder:latest \
        --type qcow2 "$container_tag"; then
        
        echo "✅ Successfully generated bootable image"
        
        # Rename to expected filename if needed
        if [ -f "output/disk.qcow2" ] && [ ! -f "output/$output_name" ]; then
            mv "output/disk.qcow2" "output/$output_name"
            echo "✅ Renamed to $output_name"
        fi
        
        # Show file info
        if [ -f "output/$output_name" ]; then
            echo "Generated image details:"
            ls -lh "output/$output_name"
            echo ""
        fi
        
        return 0
    else
        echo "❌ Failed to generate bootable image"
        return 1
    fi
}

# Function to test container functionality
test_container() {
    local container_tag="$1"
    local description="$2"
    
    echo "Testing $description container..."
    
    # Test basic container functionality
    echo "Running basic container test..."
    if podman run --rm "$container_tag" /bin/bash -c "
        echo 'Testing basic functionality...'
        echo 'OS Release:'
        cat /etc/os-release | grep PRETTY_NAME
        echo 'Kernel:'
        ls /boot/vmlinuz-* 2>/dev/null | head -1 || echo 'No kernel found'
        echo 'OSTree config:'
        test -f /etc/ostree/ostree.conf && echo 'OSTree config exists' || echo 'No OSTree config'
        echo 'Test completed successfully'
    "; then
        echo "✅ Container test passed for $description"
        return 0
    else
        echo "❌ Container test failed for $description"
        return 1
    fi
}

# Main execution
echo "======================================="
echo "STEP 1: BUILD REAL CONTAINER IMAGES"
echo "======================================="

# Track success/failure
BUILD_SUCCESS=0
BUILD_TOTAL=0

# Build minimal image
echo "Building Particle OS Minimal Image..."
BUILD_TOTAL=$((BUILD_TOTAL + 1))
if build_image "containerfiles/Containerfile.debian-trixie-minimal" \
               "localhost/particle-os-minimal:latest" \
               "Particle OS Minimal (Debian Trixie)"; then
    BUILD_SUCCESS=$((BUILD_SUCCESS + 1))
    
    # Test the minimal image
    test_container "localhost/particle-os-minimal:latest" "Minimal"
fi

echo "======================================="

# Build KDE image
echo "Building Particle OS KDE Image..."
BUILD_TOTAL=$((BUILD_TOTAL + 1))
if build_image "containerfiles/Containerfile.debian-trixie-kde" \
               "localhost/particle-os-kde:latest" \
               "Particle OS KDE (Debian Trixie)"; then
    BUILD_SUCCESS=$((BUILD_SUCCESS + 1))
    
    # Test the KDE image
    test_container "localhost/particle-os-kde:latest" "KDE"
fi

echo "======================================="
echo "STEP 2: GENERATE BOOTABLE IMAGES"
echo "======================================="

# Generate bootable images
BOOTABLE_SUCCESS=0
BOOTABLE_TOTAL=0

if [ $BUILD_SUCCESS -gt 0 ]; then
    # Generate minimal bootable image
    if podman images localhost/particle-os-minimal:latest --quiet | grep -q .; then
        echo "Generating bootable minimal image..."
        BOOTABLE_TOTAL=$((BOOTABLE_TOTAL + 1))
        if generate_bootable_image "localhost/particle-os-minimal:latest" \
                                   "particle-os-minimal.qcow2" \
                                   "Minimal Image"; then
            BOOTABLE_SUCCESS=$((BOOTABLE_SUCCESS + 1))
        fi
    fi
    
    # Generate KDE bootable image
    if podman images localhost/particle-os-kde:latest --quiet | grep -q .; then
        echo "Generating bootable KDE image..."
        BOOTABLE_TOTAL=$((BOOTABLE_TOTAL + 1))
        if generate_bootable_image "localhost/particle-os-kde:latest" \
                                   "particle-os-kde.qcow2" \
                                   "KDE Desktop Image"; then
            BOOTABLE_SUCCESS=$((BOOTABLE_SUCCESS + 1))
        fi
    fi
else
    echo "⚠️  No successful container builds, skipping bootable image generation"
fi

echo "======================================="
echo "STEP 3: RUN BASIC TESTS"
echo "======================================="

# Run basic tests if available
if [ -f "tests/real-images/test_debian_base_images.py" ]; then
    echo "Running real image tests..."
    if PYTHONPATH=. python3 -m pytest tests/real-images/ -v --tb=short; then
        echo "✅ Real image tests passed"
    else
        echo "⚠️  Some real image tests failed (expected during initial development)"
    fi
else
    echo "ℹ️  Real image tests not yet created"
fi

echo "======================================="
echo "PHASE 5 STARTUP SUMMARY"
echo "======================================="

echo "Container Build Results: $BUILD_SUCCESS/$BUILD_TOTAL successful"
echo "Bootable Image Results: $BOOTABLE_SUCCESS/$BOOTABLE_TOTAL successful"
echo ""

echo "Built Container Images:"
podman images localhost/particle-os-* --format "table {{.Repository}}:{{.Tag}}  {{.Size}}  {{.Created}}"
echo ""

echo "Generated Bootable Images:"
if [ -d "output" ]; then
    ls -lh output/*.qcow2 2>/dev/null || echo "No bootable images generated yet"
else
    echo "No output directory found"
fi
echo ""

echo "Next Steps:"
echo "1. Create test files in tests/real-images/"
echo "2. Test bootable images with QEMU:"
echo "   qemu-system-x86_64 -hda output/particle-os-kde.qcow2 -m 4G -enable-kvm"
echo "3. Run comprehensive tests:"
echo "   PYTHONPATH=. python3 -m pytest tests/real-images/ -v"
echo ""

if [ $BUILD_SUCCESS -gt 0 ]; then
    echo "🎉 Phase 5 startup successful! Ready for real image testing."
    exit 0
else
    echo "❌ Phase 5 startup had issues. Check build logs above."
    exit 1
fi
