#!/bin/bash
# build-docker.sh — Build Basalt Linux ISO in Docker with persistent cache
#
# First build:  ~30-40 min (download all packages)
# Subsequent:   ~10-15 min (packages cached in Docker volume)
#
# Usage:
#   ./build-docker.sh            # clean build, fast (cached packages)
#   ./build-docker.sh --clean    # delete all caches, full rebuild

set -e

IMAGE_NAME="basalt-builder"
PROJECT_DIR="$(pwd)"
ISO_DIR="$PROJECT_DIR/output"
VOLUME_LB="basalt-lb-cache"

# Full clean?
if [[ "$1" == "--clean" ]]; then
    echo "=== Full clean: removing cache volume ==="
    docker volume rm "$VOLUME_LB" 2>/dev/null || true
fi

mkdir -p "$ISO_DIR"

# 1. Build Docker image (cached by Docker — fast if unchanged)
echo "=== 1/3: Building Docker image ==="
docker build -t "$IMAGE_NAME" .

# 2. Ensure cache volume exists
echo "=== 2/3: Preparing cache volume ==="
docker volume create "$VOLUME_LB" 2>/dev/null || true

# 3. Run build inside container
echo "=== 3/3: Running build inside Docker ==="
echo "Cache volume: $VOLUME_LB → /var/cache/lb"
echo ""

docker run --rm --privileged \
    -v "$PROJECT_DIR":/workspace \
    -v "$VOLUME_LB":/var/cache/lb \
    "$IMAGE_NAME" \
    bash -c '
        cd /workspace && ./bldbasalt

        # ISO root:root hai (sudo se bana), is liye sudo se copy
        if ls /workspace/basaltOS/Basalt-*.iso 1>/dev/null 2>&1; then
            sudo cp /workspace/basaltOS/Basalt-*.iso /workspace/output/
            echo "=== ISO copied to output/ ==="
        fi
        echo "Build complete!"
    '

echo ""
echo "=== Done ==="
ls -lh "$ISO_DIR"/Basalt-*.iso 2>/dev/null || echo "(no ISO found)"
echo ""
echo "Next build: ./build-docker.sh"
echo "Full clean: ./build-docker.sh --clean"
