#!/bin/bash

# Integrate OSTree Structure with Simple-CLI Container
# Combines our optimized container with proper OSTree filesystem layout

set -euo pipefail

echo "🔗 Integrating OSTree Structure with Simple-CLI Container"
echo "========================================================"

# Check if we have the minimal OSTree deployment
if [ ! -d "$HOME/ostree-deployment/deploy" ]; then
    echo "❌ Error: Minimal OSTree deployment not found"
    echo "   Run: ./scripts/create-minimal-ostree.sh first"
    exit 1
fi

echo "✅ OSTree deployment found: $HOME/ostree-deployment/deploy"

# Check if simple-cli container exists
if ! podman image exists localhost/simple-cli:latest; then
    echo "❌ Error: simple-cli container image not found"
    echo "   Build with: podman build -t localhost/simple-cli:latest ."
    exit 1
fi

echo "✅ Simple-CLI container found: localhost/simple-cli:latest"

# Create integration directory
INTEGRATION_DIR="$HOME/simple-cli-ostree-integration"
echo "🔧 Creating integration directory: $INTEGRATION_DIR"
rm -rf "$INTEGRATION_DIR"
mkdir -p "$INTEGRATION_DIR"

# Copy OSTree structure
echo "📋 Copying OSTree structure..."
cp -r "$HOME/ostree-deployment/deploy"/* "$INTEGRATION_DIR/"

# Create a container that combines both
echo "🐳 Creating integrated container..."
cat > "$INTEGRATION_DIR/Dockerfile" << 'EOF'
FROM localhost/simple-cli:latest

# Apply OSTree filesystem structure
COPY . /

# Ensure atomic symlinks are correct
RUN ln -sf /usr/bin /bin && \
    ln -sf /usr/sbin /sbin && \
    ln -sf /usr/lib /lib && \
    ln -sf /usr/lib64 /lib64 && \
    ln -sf /var/home /home

# Create OSTree deployment marker
RUN mkdir -p /run && touch /run/ostree-booted

# Verify structure
RUN ls -la / | grep -E "(bin|sbin|lib|home)" && \
    echo "OSTree structure verified"

CMD ["/usr/bin/init"]
EOF

echo "✅ Integration files created"
echo ""
echo "📁 Integration directory: $INTEGRATION_DIR"
echo "🐳 Dockerfile created for OSTree integration"
echo ""
echo "🚀 Next steps:"
echo "   1. Build integrated image:"
echo "      cd $INTEGRATION_DIR"
echo "      podman build -t simple-cli-ostree:latest ."
echo "   2. Create bootable image:"
echo "      cd ../deb-bootc-image-builder"
echo "      ./scripts/bootc-image-builder.sh -o /tmp/output simple-cli-ostree:latest"
echo "   3. Test boot performance in QEMU"
echo ""
echo "📋 Files created:"
ls -la "$INTEGRATION_DIR"
