#!/bin/bash

# Use bootc properly with qcow2 via Podman
# Based on https://bootc-dev.github.io/bootc/registries-and-offline.html

set -e

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

echo "🏗️  Using bootc properly with qcow2 via Podman"
echo "=============================================="
echo "Container: $CONTAINER_IMAGE"
echo "Output: $QCOW2_FILE"
echo "Size: $SIZE"
echo ""

# Clean up
rm -f "$QCOW2_FILE"

echo "💾 Creating qcow2 disk image..."
qemu-img create -f qcow2 "$QCOW2_FILE" "$SIZE"

echo "🔧 Setting up Podman with qcow2 as drive..."
# Create a Podman container that maps the qcow2 as a drive
# This allows bootc to install to the qcow2 file as if it were a real disk

echo "📦 Running bootc install via Podman..."
# Use Podman to run bootc install with the qcow2 mapped as a drive
sudo podman run --privileged --rm \
    -v /dev:/dev \
    -v "$(pwd):/workspace" \
    -v "$QCOW2_FILE:/dev/disk/by-id/qcow2-disk" \
    --device /dev/loop0:/dev/loop0 \
    "$CONTAINER_IMAGE" \
    bootc install to-disk --source-imgref "$CONTAINER_IMAGE" /dev/disk/by-id/qcow2-disk

echo "✅ Bootc installation completed!"
echo "📊 Image info:"
qemu-img info "$QCOW2_FILE"

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