#!/bin/bash

# Use host bootc directly with qcow2 mapped as block device
# This is the proper bootc approach

set -e

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

echo "🏗️  Using host bootc with qcow2 as block device"
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 qcow2 as block device..."
# Set up the qcow2 as a loopback device so bootc can see it as a real disk
sudo losetup -f "$QCOW2_FILE"
LOOP_DEV=$(sudo losetup -j "$QCOW2_FILE" | cut -d: -f1)
echo "Loop device: $LOOP_DEV"

echo "📦 Running host bootc install to the mapped disk..."
# Use the host bootc directly to install the container to the loopback device
sudo bootc install to-disk --source-imgref "$CONTAINER_IMAGE" "$LOOP_DEV"

echo "🧹 Cleaning up loopback device..."
sudo losetup -d "$LOOP_DEV"

echo "✅ Host 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"



