#!/bin/bash

# Create a working bootc qcow2 image
# This approach creates a raw image first, then converts to qcow2

set -e

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

echo "🏗️  Creating working bootc qcow2"
echo "==============================="
echo "Container: $CONTAINER_IMAGE"
echo "Raw file: $RAW_FILE"
echo "QCOW2 file: $QCOW2_FILE"
echo "Size: $SIZE"
echo ""

# Clean up
rm -f "$RAW_FILE" "$QCOW2_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 raw disk image..."
# Create a raw disk image
dd if=/dev/zero of="$RAW_FILE" bs=1M count=10240 2>/dev/null

echo "🔧 Setting up filesystem..."
# Set up loopback device
sudo losetup -f "$RAW_FILE"
LOOP_DEV=$(sudo losetup -j "$RAW_FILE" | cut -d: -f1)

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

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

# Mount and copy files
MOUNT_DIR=$(mktemp -d)
sudo mount "${LOOP_DEV}p1" "$MOUNT_DIR"

echo "📋 Copying container contents..."
sudo cp -a "$TEMP_DIR"/* "$MOUNT_DIR"/

# Create essential directories
sudo mkdir -p "$MOUNT_DIR"/{boot,dev,proc,sys,run,tmp,var,usr,bin,sbin,etc,root,home}

# Create basic system 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"

# Create basic passwd file
echo -e "root:x:0:0:root:/root:/bin/bash\n" | sudo tee "$MOUNT_DIR/etc/passwd"

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

echo "🔄 Converting to qcow2..."
# Convert raw image to qcow2
qemu-img convert -f raw -O qcow2 "$RAW_FILE" "$QCOW2_FILE"

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

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