#!/bin/bash
# Main ISO build script - STRICTLY Docker-based
set -euo pipefail

echo "=== KNEL-Football ISO Build ==="
echo "All operations performed in Docker container"

# Configuration
readonly PROJECT_NAME="knel-football-secure"
readonly DOCKER_IMAGE="knel-football-dev:latest"
readonly BUILD_TIMEOUT="3600" # 1 hour timeout

# Function to validate Docker environment
validate_environment() {
  echo "Validating Docker environment..."

  # Check for Docker
  if ! command -v docker >/dev/null 2>&1; then
    echo "Error: Docker not found"
    exit 1
  fi

  # Check if Docker image exists
  if ! docker image inspect "$DOCKER_IMAGE" >/dev/null 2>&1; then
    echo "Error: Docker image '$DOCKER_IMAGE' not found"
    echo "Run: docker build -t $DOCKER_IMAGE ."
    exit 1
  fi

  echo "Docker environment validation successful."
}

# Function to build ISO in Docker container
build_iso() {
  echo "Building secure Debian ISO in Docker container..."

  # Clean up any existing container
  docker rm -f "$PROJECT_NAME-build" 2>/dev/null || true

  # Run build in Docker container with proper volumes
  docker run --name "$PROJECT_NAME-build" \
    --rm \
    -v "$(pwd)":/workspace:ro \
    -v "$(pwd)/tmp":/build \
    -v "$(pwd)/output":/output \
    -e TZ="UTC" \
    -e DEBIAN_FRONTEND="noninteractive" \
    -e LC_ALL="C" \
    "$DOCKER_IMAGE" \
    bash -c "
echo '=== Building KNEL-Football Secure OS ==='
echo 'All operations performed inside container'
echo 'Workspace: /workspace (read-only)'
echo 'Build: /build'
echo 'Output: /output'

# Install build tools if not present
if ! command -v lb > /dev/null 2>&1; then
    echo 'Installing build tools...'
    apt-get update -qq
    apt-get install -y live-build xorriso grub-pc-bin syslinux-utils
fi

# Create build environment
cd /build
rm -rf ./*
echo 'Configuring live-build...'
lb config \
    --distribution testing \
    --architectures amd64 \
    --archive-areas 'main contrib non-free' \
    --mode debian \
    --chroot-filesystem squashfs \
    --binary-filesystem iso9660 \
    --binary-images iso-hybrid \
    --iso-application 'KNEL-Football Secure OS' \
    --iso-publisher 'KNEL-Football Security Team' \
    --iso-volume 'KNEL-Football Secure' \
    --linux-packages 'linux-image-amd64 linux-headers-amd64' \
    --debian-installer true \
    --debian-installer-gui true \
    --win32-loader true \
    --memtest memtest86+ \
    --source false \
    --apt-indices false \
    --apt-source-archives false

# Apply configuration from workspace (copy into config/ directory created by lb config)
if [ -d /workspace/config ]; then
    echo 'Applying custom configuration...'
    cp -r /workspace/config/* ./config/
fi

# Build ISO
echo 'Starting ISO build (30-60 minutes)...'
timeout $BUILD_TIMEOUT lb build

if [ \$? -eq 0 ]; then
    echo '✓ Build completed successfully!'
    
    # Find and process ISO
    ISO_FILE=\$(find . -name '*.iso' -type f | head -1)
    if [ -n \"\$ISO_FILE\" ]; then
        echo \"✓ ISO created: \$ISO_FILE\"
        
        # Generate checksums
        sha256sum \"\$ISO_FILE\" > \"\${ISO_FILE}.sha256\"
        md5sum \"\$ISO_FILE\" > \"\${ISO_FILE}.md5\"
        
        # Create KNEL-Football branded name
        FINAL_ISO=\"${PROJECT_NAME}.iso\"
        mv \"\$ISO_FILE\" \"\$FINAL_ISO\"
        mv \"\${ISO_FILE}.sha256\" \"\${FINAL_ISO}.sha256\"
        mv \"\${ISO_FILE}.md5\" \"\${FINAL_ISO}.md5\"
        
        # Copy artifacts to output volume
        cp \"\$FINAL_ISO\" \"\${FINAL_ISO}.sha256\" \"\${FINAL_ISO}.md5\" /output/
        
        # Create build report
        cat > /output/BUILD-REPORT.txt << REPORT
KNEL-Football Secure OS Build Report
=================================
Build Date: \$(date)
Build Environment: Docker Container ($DOCKER_IMAGE)
Version: unversioned (latest build)
Architecture: x86_64

Files Created:
- $PROJECT_NAME.iso (bootable ISO)
- $PROJECT_NAME.iso.sha256 (SHA256 checksum)
- $PROJECT_NAME.iso.md5 (MD5 checksum)

Technical Specifications:
- Base Distribution: Debian Testing
- Boot Support: Hybrid UEFI/Legacy BIOS
- Filesystem: SquashFS + ISO9660
- Package Manager: apt
- Init System: systemd

Features:
- Debian Installer with GUI
- Full firmware support
- Security configurations
- Memtest86+ memory testing

Build Status: SUCCESSFUL

Next Steps:
1. Test ISO on target hardware
2. Validate installation process
3. Apply KNEL-Football security configurations
4. Deploy to production environment

ISO Information:
Type: Hybrid (UEFI + Legacy BIOS compatible)
Checksum: SHA256 (see .sha256 file)

Contact: KNEL-Football IT Security Team
Generated: \$(date)
REPORT
        
        echo '✓ Build report created'
        echo '✓ All artifacts copied to /output/'
        
        # Display ISO info
        if [ -f \"/output/\$FINAL_ISO\" ]; then
            echo ''
            echo 'ISO Details:'
            echo \"File: \$FINAL_ISO\"
            echo \"Size: \$(du -h \"/output/\$FINAL_ISO\" | cut -f1)\"
            echo \"SHA256: \$(cat \"/output/\${FINAL_ISO}.sha256\" | cut -d' ' -f1)\"
        fi
        
    else
        echo '✗ No ISO file found'
        exit 1
    fi
else
    echo '✗ Build failed or timed out'
    exit 1
fi
"

  # Check if build succeeded
  echo ""
  echo "=== BUILD COMPLETION CHECK ==="

  if [ -f "output/$PROJECT_NAME.iso" ]; then
    echo "[OK] BUILD SUCCESSFUL!"
    echo "[OK] ISO created: $PROJECT_NAME.iso"
    echo "[OK] Size: $(du -h "output/$PROJECT_NAME.iso" | cut -f1)"
    echo "[OK] SHA256: $(cut -d' ' -f1 < "output/$PROJECT_NAME.iso.sha256")"
    echo "All operations performed in Docker container - NO host modifications"
    return 0
  else
    echo "[FAIL] BUILD FAILED"
    echo "Check Docker container output for errors"
    return 1
  fi
}

# Main execution
main() {
  echo "Starting KNEL-Football secure ISO build..."

  # Ensure output directory exists
  mkdir -p output
  mkdir -p tmp

  validate_environment
  build_iso

  echo "Build process completed successfully!"
  echo "All operations performed in Docker container - NO host system modifications"
}

main "$@"
