#!/bin/bash

echo "Creating simple bootable qcow2..."

# Clean up
rm -f debian-bootc-simple.qcow2

# Create qcow2
qemu-img create -f qcow2 debian-bootc-simple.qcow2 1G

# Export container to temp dir
TEMP_DIR=$(mktemp -d)
echo "Exporting container to $TEMP_DIR"
podman create git.raines.xyz/particle-os/debian-bootc:latest-with-fixes
CONTAINER_ID=$(podman create git.raines.xyz/particle-os/debian-bootc:latest-with-fixes)
podman export "$CONTAINER_ID" | tar -xC "$TEMP_DIR"
podman rm "$CONTAINER_ID"

# Create raw image
dd if=/dev/zero of=temp.raw bs=1M count=100 2>/dev/null

# Set up loopback
sudo losetup -f temp.raw
LOOP_DEV=$(sudo losetup -j temp.raw | cut -d: -f1)

# Create partition
echo -e "n\np\n1\n\n\nt\n83\na\nw" | sudo fdisk "$LOOP_DEV" >/dev/null 2>&1
sudo partprobe "$LOOP_DEV"

# Format
sudo mkfs.ext4 -F "${LOOP_DEV}p1"

# Mount and copy
MOUNT_DIR=$(mktemp -d)
sudo mount "${LOOP_DEV}p1" "$MOUNT_DIR"
sudo cp -a "$TEMP_DIR"/* "$MOUNT_DIR"/

# Install GRUB
sudo grub-install --target=i386-pc --boot-directory="$MOUNT_DIR/boot" --force "$LOOP_DEV"

# Create GRUB config
sudo mkdir -p "$MOUNT_DIR/boot/grub"
sudo tee "$MOUNT_DIR/boot/grub/grub.cfg" > /dev/null << 'EOF'
set timeout=5
set default=0
menuentry "Debian Bootc" {
    linux /boot/vmlinuz root=/dev/sda1 ro quiet
    initrd /boot/initrd.img
}
EOF

# Unmount
sudo umount "$MOUNT_DIR"
sudo losetup -d "$LOOP_DEV"
rmdir "$MOUNT_DIR"

# Convert to qcow2
qemu-img convert -f raw -O qcow2 temp.raw debian-bootc-simple.qcow2

# Cleanup
rm -f temp.raw
rm -rf "$TEMP_DIR"

echo "Created debian-bootc-simple.qcow2"
qemu-img info debian-bootc-simple.qcow2



