#!/bin/bash

# Create a proper bootc qcow2 image
# This creates a larger, bootable qcow2 from the bootc container

set -e

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

echo "🏗️  Creating bootable bootc qcow2"
echo "================================="
echo "Container: $CONTAINER_IMAGE"
echo "Output: $OUTPUT_FILE"
echo "Size: $SIZE"
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 proper 10GB qcow2 image
qemu-img create -f qcow2 "$OUTPUT_FILE" "$SIZE"

echo "🔧 Setting up filesystem..."
# Use guestfish to set up the filesystem properly
if command -v guestfish >/dev/null 2>&1; then
    echo "📁 Using guestfish to set up filesystem..."
    guestfish -a "$OUTPUT_FILE" << EOF
run
part-disk /dev/sda mbr
part-set-bootable /dev/sda 1 true
mkfs ext4 /dev/sda1
mount /dev/sda1 /
copy-in $TEMP_DIR/* /
mkdir /boot
mkdir /dev
mkdir /proc
mkdir /sys
mkdir /run
mkdir /tmp
write /etc/fstab "/dev/sda1 / ext4 defaults 0 1\n"
write /etc/hostname "debian-bootc\n"
write /etc/hosts "127.0.0.1 localhost\n127.0.1.1 debian-bootc\n"
umount /
EOF
else
    echo "📁 Using manual approach with loopback..."
    # Manual approach using loopback
    sudo losetup -f "$OUTPUT_FILE"
    LOOP_DEV=$(sudo losetup -j "$OUTPUT_FILE" | cut -d: -f1)
    
    # Create partition table and partition
    echo -e "n\np\n1\n\n\nt\n83\nw" | sudo fdisk "$LOOP_DEV"
    sudo partprobe "$LOOP_DEV"
    
    # Format and mount
    sudo mkfs.ext4 -F "${LOOP_DEV}p1"
    MOUNT_DIR=$(mktemp -d)
    sudo mount "${LOOP_DEV}p1" "$MOUNT_DIR"
    
    # Copy files
    sudo cp -a "$TEMP_DIR"/* "$MOUNT_DIR"/
    sudo mkdir -p "$MOUNT_DIR"/{boot,dev,proc,sys,run,tmp}
    
    # Create basic config files
    echo "/dev/sda1 / ext4 defaults 0 1" | sudo tee "$MOUNT_DIR/etc/fstab"
    echo "debian-bootc" | sudo tee "$MOUNT_DIR/etc/hostname"
    echo -e "127.0.0.1 localhost\n127.0.1.1 debian-bootc" | sudo tee "$MOUNT_DIR/etc/hosts"
    
    # Unmount and cleanup
    sudo umount "$MOUNT_DIR"
    sudo losetup -d "$LOOP_DEV"
    rmdir "$MOUNT_DIR"
fi

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

echo "✅ Created bootable qcow2: $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"



