#!/bin/bash

# Final bootc container to qcow2 converter
# Creates a proper qcow2 image from the bootc container

set -e

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

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

# Clean up
rm -f "$OUTPUT_FILE"

echo "📦 Exporting container contents..."
TEMP_DIR=$(mktemp -d)
CONTAINER_ID=$(podman create "$CONTAINER_IMAGE")
podman export "$CONTAINER_ID" | tar -xC "$TEMP_DIR"
podman rm "$CONTAINER_ID"

echo "💾 Creating qcow2 image..."
# Create a 10GB qcow2 image
qemu-img create -f qcow2 "$OUTPUT_FILE" 10G

echo "🔧 Setting up filesystem..."
# Use NBD to mount the qcow2
sudo modprobe nbd max_part=16
sudo qemu-nbd -c /dev/nbd0 "$OUTPUT_FILE"

# Create filesystem
sudo mkfs.ext4 /dev/nbd0

# Mount and copy files
MOUNT_DIR=$(mktemp -d)
sudo mount /dev/nbd0 "$MOUNT_DIR"
sudo cp -a "$TEMP_DIR"/* "$MOUNT_DIR"/

# Create basic boot files if they don't exist
sudo mkdir -p "$MOUNT_DIR"/{boot,dev,proc,sys,run,tmp}

# Unmount and disconnect
sudo umount "$MOUNT_DIR"
sudo qemu-nbd -d /dev/nbd0

echo "🧹 Cleaning up..."
rm -rf "$TEMP_DIR" "$MOUNT_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"



