#!/bin/bash
# Script to create a bootable ISO with isolinux bootloader

set -e

echo "Creating bootable ISO with isolinux bootloader..."

# Create build directory
mkdir -p build

# Extract real kernel and initrd from container on the host first
echo "Extracting kernel and initrd from container..."
mkdir -p build/temp-boot

# Create temporary container to extract boot files
podman create --name temp-boot-extractor debian-atomic-installer:latest

# Extract specific kernel and initrd files we know exist
echo "Extracting kernel: /boot/vmlinuz-6.12.38+deb13-amd64"
if podman cp temp-boot-extractor:/boot/vmlinuz-6.12.38+deb13-amd64 build/temp-boot/vmlinuz 2>/dev/null; then
    echo "✅ Kernel extracted successfully"
else
    echo "Warning: Kernel not found, using placeholder"
    echo 'This is a placeholder kernel' > build/temp-boot/vmlinuz
fi

echo "Extracting initrd: /boot/initrd.img-6.12.38+deb13-amd64"
if podman cp temp-boot-extractor:/boot/initrd.img-6.12.38+deb13-amd64 build/temp-boot/initrd.img 2>/dev/null; then
    echo "✅ Initrd extracted successfully"
else
    echo "Warning: Initrd not found, using placeholder"
    echo 'This is a placeholder initrd' > build/temp-boot/initrd.img
fi

# Clean up temporary container
podman rm temp-boot-extractor

echo "Creating bootable ISO using podman..."

# Use podman to create everything inside the container
podman run --rm \
    -v "$(pwd)/build:/output:Z" \
    -v "$(pwd)/build/temp-boot:/host-boot:ro" \
    -v "$(pwd):/host-workspace:ro" \
    debian:trixie \
    bash -c "
        # Configure apt-cacher-ng proxy if available
        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 required packages
        apt-get update
        apt-get install -y genisoimage isolinux squashfs-tools
        
        # Create working directory
        mkdir -p /tmp/iso-content
        cd /tmp/iso-content
        
        # Create basic ISO structure
        mkdir -p boot/grub
        mkdir -p isolinux
        
        # Copy real kernel and initrd from host
        echo 'Using real kernel and initrd from container...'
        cp /host-boot/vmlinuz boot/vmlinuz
        cp /host-boot/initrd.img boot/initrd.img
        
        # Create live filesystem directory structure
        echo 'Creating live filesystem structure...'
        mkdir -p live
        
        # Use pre-extracted container filesystem for live system
        echo 'Using pre-extracted container filesystem...'
        
        if [ -d /host-workspace/build/container-filesystem ]; then
            echo 'Copying complete container filesystem from host...'
            cp -a /host-workspace/build/container-filesystem filesystem
            echo 'Container filesystem copied successfully!'
        else
            echo 'WARNING: Pre-extracted filesystem not found!'
            echo 'Please run ./scripts/extract-container-filesystem.sh first'
            echo 'Creating minimal fallback filesystem...'
            
            # Fallback: create minimal structure
            mkdir -p filesystem
            mkdir -p filesystem/{bin,sbin,usr/{bin,sbin,lib,lib64,share},lib,lib64}
            mkdir -p filesystem/{etc,var,tmp,root,home,mnt,media,opt,srv}
            mkdir -p filesystem/{proc,sys,dev,run}
            
            # Create a basic init script as fallback
            cat > filesystem/sbin/init << 'FALLBACK_EOF'
#!/bin/sh
echo \"Debian Atomic Live System (Minimal)\"
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev
echo \"Live system ready - entering shell\"
/bin/sh
FALLBACK_EOF
            chmod +x filesystem/sbin/init
        fi
        
        # Prepare the live system
        echo 'Preparing live system filesystem...'
        
        # The init script should already be created by extract-container-filesystem.sh
        if [ -x filesystem/sbin/init ]; then
            echo 'Init script found in extracted filesystem!'
        else
            echo 'Creating fallback init script...'
            mkdir -p filesystem/sbin
            cat > filesystem/sbin/init << 'INIT_EOF'
#!/bin/bash
echo \"=== Debian Atomic Desktop Live System ===\"
mount -t proc proc /proc
mount -t sysfs sysfs /sys  
mount -t devtmpfs devtmpfs /dev
mount -t tmpfs tmpfs /run
mount -t tmpfs tmpfs /tmp
echo \"Live system ready!\"
exec /bin/bash
INIT_EOF
            chmod +x filesystem/sbin/init
        fi
        
        # Create the SquashFS filesystem with better compression
        echo 'Creating SquashFS filesystem from full container...'
        mksquashfs filesystem live/filesystem.squashfs -comp xz -Xbcj x86 -b 1M -Xdict-size 100%
        
        # Create GRUB configuration
        cat > boot/grub/grub.cfg << 'EOF'
set timeout=5
set default=0

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

menuentry 'Debian Atomic Desktop Installer (Safe Mode)' {
    linux /boot/vmlinuz root=live:CDLABEL=DEBIAN_ATOMIC nomodeset
    initrd /boot/initrd.img
}
EOF
        
        # Create isolinux configuration
        cat > isolinux/isolinux.cfg << 'EOF'
DEFAULT install
TIMEOUT 50
PROMPT 1

LABEL install
    KERNEL /boot/vmlinuz
    INITRD /boot/initrd.img
    APPEND boot=live live-media-path=/live/ quiet splash
    
LABEL install-safe
    KERNEL /boot/vmlinuz
    INITRD /boot/initrd.img
    APPEND boot=live live-media-path=/live/ nomodeset quiet
EOF
        
        # Copy isolinux files
        cp /usr/lib/ISOLINUX/isolinux.bin isolinux/ 2>/dev/null || echo 'isolinux.bin not found'
        cp /usr/lib/syslinux/modules/bios/ldlinux.c32 isolinux/ 2>/dev/null || echo 'ldlinux.c32 not found'
        
        # Create a simple README
        echo 'Debian Atomic Desktop Installer ISO' > README.txt
        echo 'This is a bootable ISO for testing.' >> README.txt
        
        # List contents to debug
        echo 'Contents of /tmp/iso-content:'
        ls -la /tmp/iso-content/
        echo 'Contents of isolinux directory:'
        ls -la /tmp/iso-content/isolinux/
        
        # Create bootable ISO with proper El Torito boot specification
        genisoimage -o /tmp/debian-atomic-installer-bootable.iso \
            -b isolinux/isolinux.bin \
            -c isolinux/boot.cat \
            -no-emul-boot \
            -boot-load-size 4 \
            -boot-info-table \
            -r \
            -J \
            -V 'DEBIAN_ATOMIC' \
            .
        
        # Copy ISO to output directory
        cp /tmp/debian-atomic-installer-bootable.iso /output/
        echo 'Bootable ISO created and copied to output directory'
    "

echo "Bootable ISO created: build/debian-atomic-installer-bootable.iso"
if [ -f "build/debian-atomic-installer-bootable.iso" ]; then
    echo "Size: $(du -h build/debian-atomic-installer-bootable.iso | cut -f1)"
    echo "✅ Bootable ISO creation completed!"
else
    echo "❌ Bootable ISO creation failed!"
    exit 1
fi 