#!/bin/bash

# Create a bootable qcow2 from bootc container
set -e

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

echo "Creating bootable qcow2 from bootc container..."

# Clean up
rm -f "$QCOW2_FILE"

# Export container
TEMP_DIR=$(mktemp -d)
CONTAINER_ID=$(podman create "$CONTAINER_IMAGE")
podman export "$CONTAINER_ID" | tar -xC "$TEMP_DIR"
podman rm "$CONTAINER_ID"

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

# Set up loopback
sudo losetup -f "$RAW_FILE"
LOOP_DEV=$(sudo losetup -j "$RAW_FILE" | 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 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,var,usr,bin,sbin,etc,root,home}

# Create basic config
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"
echo -e "root:x:0:0:root:/root:/bin/bash\n" | sudo tee "$MOUNT_DIR/etc/passwd"

# Install GRUB
echo "Installing 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 and convert
sudo umount "$MOUNT_DIR"
sudo losetup -d "$LOOP_DEV"
rmdir "$MOUNT_DIR"

# Convert to qcow2
qemu-img convert -f raw -O qcow2 "$RAW_FILE" "$QCOW2_FILE"
rm -f "$RAW_FILE"
rm -rf "$TEMP_DIR"

echo "Created: $QCOW2_FILE"
qemu-img info "$QCOW2_FILE"



