#!/bin/bash

# Configuration
IMAGE_NAME="mcx-image-dev-mcx-intel-2025.03-0-g0e9d0e9.wic"
[ -n "$1" ] && IMAGE_NAME="$1"

# Remove .xz or .gz extension if present to get the base name
BASE_NAME="${IMAGE_NAME%.xz}"
BASE_NAME="${BASE_NAME%.gz}"

# Define compressed versions
XZ_IMAGE="${BASE_NAME}.xz"
GZ_IMAGE="${BASE_NAME}.gz"

decompress_file() {
    local file="$1"
    case "$file" in
        *.xz)
            echo "Uncompressing .xz image..."
            xz -dk "$file"
            ;;
        *.gz)
            echo "Uncompressing .gz image..."
            gunzip -k "$file"
            ;;
        *)
            echo "Error: Unknown compression format for $file"
            return 1
            ;;
    esac

    if [ $? -ne 0 ]; then
        echo "Error: Failed to uncompress image"
        return 1
    fi
    echo "Image uncompressed successfully"
    return 0
}

# Check if uncompressed image exists
if [ ! -f "$BASE_NAME" ]; then
    # Check for compressed files in order
    if [ -f "$IMAGE_NAME" ]; then
        # Original filename is a compressed file
        decompress_file "$IMAGE_NAME" || exit 1
    elif [ -f "$XZ_IMAGE" ]; then
        decompress_file "$XZ_IMAGE" || exit 1
    elif [ -f "$GZ_IMAGE" ]; then
        decompress_file "$GZ_IMAGE" || exit 1
    else
        echo "Error: No image found. Tried:"
        echo "- $BASE_NAME"
        echo "- $XZ_IMAGE"
        echo "- $GZ_IMAGE"
        exit 1
    fi
else
    echo "Using existing uncompressed image: $BASE_NAME"
fi

# Start QEMU
echo "Starting QEMU..."
sudo qemu-system-x86_64 \
    -drive file="$BASE_NAME",format=raw,if=virtio \
    -m 4096 \
    -bios /usr/share/ovmf/OVMF.fd \
    -cpu Skylake-Client \
    -smp cores=4 \
    -enable-kvm \
    -netdev tap,id=net0,ifname=tap0,script=network-up.sh,downscript=network-down.sh \
    -device virtio-net-pci,netdev=net0 \
    -nographic
