#!/bin/bash
# Script to create a bootable ISO using bootc in a Debian container

set -e

echo "Creating bootable ISO using bootc in Debian 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

echo "Running bootc in Debian container to create ISO..."

# Copy the image to a temporary name that can be accessed from the container
echo "Preparing image for container access..."
podman tag debian-atomic-installer:latest localhost/debian-atomic-installer:latest

# Run bootc in a Debian container
podman run --rm \
    --privileged \
    -v "$(pwd)/build:/output" \
    -w /output \
    debian:trixie \
    bash -c "
        # Configure apt-cacher-ng proxy
        if [ -n \"$APT_CACHER_NG_PROXY\" ]; then
            echo \"Acquire::http::Proxy \\\"$APT_CACHER_NG_PROXY\\\";\" > /etc/apt/apt.conf.d/99proxy
            echo \"Acquire::https::Proxy \\\"$APT_CACHER_NG_PROXY\\\";\" >> /etc/apt/apt.conf.d/99proxy
        fi
        
        # Update and install bootc
        apt-get update
        apt-get install -y curl
        
        # Install bootc from GitHub releases
        curl -L https://github.com/containers/bootc/releases/download/v1.5.1/bootc-x86_64-unknown-linux-gnu.tar.gz | tar -xz
        mv bootc /usr/local/bin/
        chmod +x /usr/local/bin/bootc
        
        # Try to create ISO using bootc
        echo 'Attempting to create ISO with bootc...'
        if bootc container build-iso debian-atomic-installer:latest --output debian-atomic-installer.iso; then
            echo 'ISO created successfully with bootc!'
        else
            echo 'bootc build-iso failed, falling back to manual ISO creation...'
            # Fallback to manual ISO creation
            apt-get install -y xorriso squashfs-tools podman
            # Extract container and create ISO manually
            mkdir -p /tmp/iso
            mkdir -p /tmp/iso/boot
            
            # Try to access the container image directly
            echo 'Extracting container filesystem...'
            podman create --name temp-installer debian-atomic-installer:latest || echo 'Container creation failed, using basic structure'
            
            if podman ps -a | grep -q temp-installer; then
                podman export temp-installer | tar -x -C /tmp/iso || echo 'Export failed, using basic structure'
                podman rm temp-installer
                
                # Extract kernel and initrd from the container
                echo 'Extracting kernel and initrd...'
                podman create --name temp-kernel debian-atomic-installer:latest
                if podman ps -a | grep -q temp-kernel; then
                    podman cp temp-kernel:/boot/vmlinuz-$(uname -r) /tmp/iso/boot/vmlinuz 2>/dev/null || echo 'Kernel not found in container'
                    podman cp temp-kernel:/boot/initrd.img-$(uname -r) /tmp/iso/boot/initrd.img 2>/dev/null || echo 'Initrd not found in container'
                    podman rm temp-kernel
                fi
            fi
            
            # Create basic kernel and initrd placeholders if not found
            if [ ! -f /tmp/iso/boot/vmlinuz ]; then
                echo 'Creating basic kernel placeholder...'
                echo 'This is a placeholder kernel' > /tmp/iso/boot/vmlinuz
            fi
            if [ ! -f /tmp/iso/boot/initrd.img ]; then
                echo 'Creating basic initrd placeholder...'
                echo 'This is a placeholder initrd' > /tmp/iso/boot/initrd.img
            fi
            
            # Create proper bootloader structure
            mkdir -p /tmp/iso/boot/grub/x86_64-efi
            mkdir -p /tmp/iso/boot/grub/i386-pc
            mkdir -p /tmp/iso/isolinux
            
            # Install GRUB and create bootloader files
            echo 'Installing GRUB bootloader...'
            apt-get install -y grub-efi-amd64 grub-pc-bin grub-common isolinux
            
            # Create GRUB configuration
            cat > /tmp/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
            
            # Copy GRUB bootloader files
            cp /usr/lib/grub/x86_64-efi/*.mod /tmp/iso/boot/grub/x86_64-efi/ 2>/dev/null || echo 'EFI modules not found'
            cp /usr/lib/grub/i386-pc/*.mod /tmp/iso/boot/grub/i386-pc/ 2>/dev/null || echo 'PC modules not found'
            cp /usr/lib/grub/x86_64-efi/grub.efi /tmp/iso/boot/grub/x86_64-efi/ 2>/dev/null || echo 'EFI grub not found'
            cp /usr/lib/grub/i386-pc/grub.efi /tmp/iso/boot/grub/i386-pc/ 2>/dev/null || echo 'PC grub not found'
            
            # Create isolinux files for legacy boot
            cp /usr/lib/ISOLINUX/isolinux.bin /tmp/iso/isolinux/ 2>/dev/null || echo 'isolinux.bin not found'
            cp /usr/lib/syslinux/modules/bios/ldlinux.c32 /tmp/iso/isolinux/ 2>/dev/null || echo 'ldlinux.c32 not found'
            
            # Create isolinux config
            cat > /tmp/iso/isolinux/isolinux.cfg << 'EOF'
DEFAULT install
TIMEOUT 50
PROMPT 1

LABEL install
    KERNEL /boot/vmlinuz
    APPEND root=live:CDLABEL=DEBIAN_ATOMIC_INSTALLER quiet initrd=/boot/initrd.img
    
LABEL install-safe
    KERNEL /boot/vmlinuz
    APPEND root=live:CDLABEL=DEBIAN_ATOMIC_INSTALLER nomodeset initrd=/boot/initrd.img
EOF
            
            # Create bootable ISO with proper bootloader
            xorrisofs -o 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' \
                /tmp/iso/
        fi
    "

echo "ISO creation completed!"
if [ -f "build/debian-atomic-installer.iso" ]; then
    echo "ISO created: build/debian-atomic-installer.iso"
    echo "Size: $(du -h build/debian-atomic-installer.iso | cut -f1)"
else
    echo "Warning: ISO file not found in expected location"
fi 