#!/bin/bash

# Simple bootc container to qcow2 converter
# Creates a basic bootable qcow2 from the bootc container

set -e

CONTAINER_IMAGE="git.raines.xyz/particle-os/debian-bootc:latest-with-fixes"
OUTPUT_FILE="bootc-simple.qcow2"

echo "🏗️  Creating simple bootc qcow2"
echo "=============================="
echo "Container: $CONTAINER_IMAGE"
echo "Output: $OUTPUT_FILE"
echo ""

# Clean up
rm -f "$OUTPUT_FILE"

echo "📦 Pulling container image..."
podman pull "$CONTAINER_IMAGE"

echo "💾 Creating qcow2 from container..."
# Use virt-make-fs to create a filesystem image from container
TEMP_DIR=$(mktemp -d)
echo "📁 Using temp directory: $TEMP_DIR"

# Export container to directory
echo "📋 Exporting container contents..."
CONTAINER_ID=$(podman create "$CONTAINER_IMAGE")
podman export "$CONTAINER_ID" | tar -xC "$TEMP_DIR"
podman rm "$CONTAINER_ID"

# Create a bootable qcow2 image using virt-make-fs
echo "🔧 Creating bootable qcow2..."
if command -v virt-make-fs >/dev/null 2>&1; then
    virt-make-fs --format=qcow2 --size=10G "$TEMP_DIR" "$OUTPUT_FILE"
else
    echo "📦 virt-make-fs not available, using manual approach..."
    # Create qcow2 manually
    qemu-img create -f qcow2 "$OUTPUT_FILE" 10G
    
    # Format as ext4
    TEMP_LOOP=$(sudo losetup -f --show "$OUTPUT_FILE")
    sudo mkfs.ext4 -F "$TEMP_LOOP"
    
    # Mount and copy files
    TEMP_MOUNT=$(mktemp -d)
    sudo mount "$TEMP_LOOP" "$TEMP_MOUNT"
    sudo cp -a "$TEMP_DIR"/* "$TEMP_MOUNT"/
    
    # Unmount and cleanup
    sudo umount "$TEMP_MOUNT"
    sudo losetup -d "$TEMP_LOOP"
    rmdir "$TEMP_MOUNT"
fi

echo "🧹 Cleaning up..."
rm -rf "$TEMP_DIR"

echo "✅ Created qcow2 image: $OUTPUT_FILE"
echo "📊 Image info:"
qemu-img info "$OUTPUT_FILE"

echo ""
echo "🚀 To boot this image:"
echo "   qemu-system-x86_64 -m 2G -drive file=$OUTPUT_FILE,format=qcow2 -netdev user,id=net0 -device e1000,netdev=net0 -nographic"



