#!/bin/bash
# Script to create a bootable ISO from the installer container

set -e

echo "Creating bootable ISO from installer container..."

# Check if container image exists
if ! podman image exists debian-atomic-installer:latest; then
    echo "Error: Container image debian-atomic-installer:latest not found"
    echo "Please build the installer first with: just build-installer"
    exit 1
fi

# Create build directory
mkdir -p build/iso

echo "Extracting container filesystem..."
# Extract the container filesystem
podman create --name temp-installer debian-atomic-installer:latest
podman export temp-installer | tar -x -C build/iso
podman rm temp-installer

echo "Setting up bootloader..."
# Create basic bootloader structure
mkdir -p build/iso/boot/grub
mkdir -p build/iso/isolinux

# Create a basic GRUB configuration
cat > build/iso/boot/grub/grub.cfg << 'EOF'
set timeout=5
set default=0

menuentry "Debian Atomic Desktop Installer" {
    linux /boot/vmlinuz root=live:CDLABEL=DEBIAN_ATOMIC_INSTALLER quiet
    initrd /boot/initrd.img
}

menuentry "Debian Atomic Desktop Installer (Safe Mode)" {
    linux /boot/vmlinuz root=live:CDLABEL=DEBIAN_ATOMIC_INSTALLER nomodeset
    initrd /boot/initrd.img
}
EOF

echo "Creating ISO..."
# Create the ISO using genisoimage or xorrisofs
if command -v xorrisofs &> /dev/null; then
    xorrisofs -o build/debian-atomic-installer.iso \
        -b isolinux/isolinux.bin \
        -c isolinux/boot.cat \
        -boot-info-table \
        -no-emul-boot \
        -boot-load-size 4 \
        -r \
        -V "DEBIAN_ATOMIC_INSTALLER" \
        build/iso/
elif command -v genisoimage &> /dev/null; then
    genisoimage -o build/debian-atomic-installer.iso \
        -b isolinux/isolinux.bin \
        -c isolinux/boot.cat \
        -boot-info-table \
        -no-emul-boot \
        -boot-load-size 4 \
        -r \
        -V "DEBIAN_ATOMIC_INSTALLER" \
        build/iso/
else
    echo "Error: Neither xorrisofs nor genisoimage found"
    echo "Please install one of them:"
    echo "  sudo apt install xorriso"
    echo "  sudo apt install genisoimage"
    exit 1
fi

echo "ISO created successfully: build/debian-atomic-installer.iso"
echo "Size: $(du -h build/debian-atomic-installer.iso | cut -f1)" 