#!/bin/bash

# Debian Atomic Desktop - Prepare Atomic Image Script
# This script prepares the atomic image for embedding in the live ISO

set -e

# Configuration
ATOMIC_IMAGE="debian-atomic:latest"
LIVE_MOUNT="/run/archivemount"
IMAGE_TAR="atomic-image.tar"

echo "Preparing atomic image for live ISO..."

# Check if we're running in the live environment
if [ -d "$LIVE_MOUNT" ]; then
    echo "Running in live environment, preparing atomic image..."
    
    # Create directory for atomic image
    mkdir -p "$LIVE_MOUNT/atomic"
    
    # Save the atomic image to tar file
    if podman image exists "$ATOMIC_IMAGE"; then
        echo "Saving atomic image to $IMAGE_TAR..."
        podman save -o "$LIVE_MOUNT/atomic/$IMAGE_TAR" "$ATOMIC_IMAGE"
        
        # Create deployment script
        cat > "$LIVE_MOUNT/atomic/deploy.sh" << 'EOF'
#!/bin/bash
# Deploy atomic image script

set -e

ATOMIC_IMAGE="debian-atomic:latest"
IMAGE_TAR="atomic-image.tar"
TARGET_DEVICE="/dev/sda"

echo "Deploying Debian Atomic Desktop..."

# Load the atomic image
if [ -f "$IMAGE_TAR" ]; then
    echo "Loading atomic image..."
    podman load -i "$IMAGE_TAR"
fi

# Install using bootc
echo "Installing atomic image to $TARGET_DEVICE..."
bootc install to-disk --device "$TARGET_DEVICE" --replace-os --image "$ATOMIC_IMAGE"

echo "Atomic installation complete!"
EOF
        
        chmod +x "$LIVE_MOUNT/atomic/deploy.sh"
        echo "Atomic image prepared successfully."
    else
        echo "Warning: Atomic image $ATOMIC_IMAGE not found."
        echo "Installation will attempt to pull from registry."
    fi
else
    echo "Not in live environment, skipping atomic image preparation."
fi

echo "Atomic image preparation complete." 