#!/bin/bash

# Test Boot Performance Script
# Tests the boot performance of our optimized simple-cli image

set -euo pipefail

IMAGE_PATH="/tmp/simple-cli-output/simple-cli_latest.qcow2"
OUTPUT_LOG="/tmp/boot-performance-test.log"

echo "🚀 Testing Boot Performance of Optimized Simple-CLI Image"
echo "========================================================"
echo "Image: $IMAGE_PATH"
echo "Output log: $OUTPUT_LOG"
echo ""

# Check if image exists
if [ ! -f "$IMAGE_PATH" ]; then
    echo "❌ Error: Image not found at $IMAGE_PATH"
    exit 1
fi

echo "✅ Image found, starting boot performance test..."
echo ""

# Function to clean up QEMU processes
cleanup() {
    echo "🧹 Cleaning up QEMU processes..."
    pkill -f "qemu-system-x86_64.*simple-cli" 2>/dev/null || true
    sleep 2
}

# Set up cleanup on exit
trap cleanup EXIT

echo "⏱️  Starting QEMU with optimized image..."
echo "📝 Boot output will be logged to: $OUTPUT_LOG"
echo ""

# Start QEMU and capture output
echo "Starting boot test at $(date)" > "$OUTPUT_LOG"
echo "=========================================" >> "$OUTPUT_LOG"

# Run QEMU with timeout and capture output
timeout 60 qemu-system-x86_64 \
    -m 2G \
    -smp 2 \
    -drive file="$IMAGE_PATH",format=qcow2 \
    -nographic \
    -serial mon:stdio \
    -display none \
    2>&1 | tee -a "$OUTPUT_LOG" &

QEMU_PID=$!
echo "QEMU started with PID: $QEMU_PID"

# Wait for QEMU to start booting
sleep 5

# Monitor the boot process
echo "🔍 Monitoring boot process..."
BOOT_START=$(date +%s)
BOOT_COMPLETE=false

while [ $(( $(date +%s) - BOOT_START )) -lt 60 ]; do
    if ! kill -0 $QEMU_PID 2>/dev/null; then
        echo "✅ QEMU process completed"
        BOOT_COMPLETE=true
        break
    fi
    
    # Check if we've reached a login prompt or similar
    if grep -q "login\|Login\|simple@" "$OUTPUT_LOG" 2>/dev/null; then
        echo "✅ Boot completed - login prompt detected"
        BOOT_COMPLETE=true
        break
    fi
    
    sleep 1
done

# Calculate boot time
BOOT_END=$(date +%s)
BOOT_TIME=$((BOOT_END - BOOT_START))

echo ""
echo "📊 Boot Performance Results"
echo "=========================="
echo "Boot time: ${BOOT_TIME} seconds"
echo "Status: $([ "$BOOT_COMPLETE" = true ] && echo "✅ SUCCESS" || echo "❌ TIMEOUT")"
echo ""

# Show boot log summary
echo "📋 Boot Log Summary"
echo "==================="
if [ -f "$OUTPUT_LOG" ]; then
    echo "Last 20 lines of boot output:"
    tail -20 "$OUTPUT_LOG" | sed 's/^/  /'
else
    echo "No boot log found"
fi

echo ""
echo "🎯 Boot Performance Analysis Complete!"
echo "Check $OUTPUT_LOG for full boot details"
