#!/bin/bash
# Omarchy Repository Package Builder - Docker Isolated
# Builds packages in Docker without affecting the host system

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Repository paths
REPO_DIR="/home/ryan/Dev/omarchy-repo"
ARCH_DIR="$REPO_DIR/x86_64"
BUILD_DIR="$REPO_DIR/build"

# Create directories if they don't exist
mkdir -p "$ARCH_DIR" "$BUILD_DIR"

# Function to print colored messages
print_msg() {
    local color=$1
    local msg=$2
    echo -e "${color}${msg}${NC}"
}


# Function to build Docker image
build_docker_image() {
    print_msg "$BLUE" "==> Building Docker image..."
    
    # Check if Dockerfile exists
    if [[ ! -f "$BUILD_DIR/Dockerfile" ]]; then
        print_msg "$RED" "Error: Dockerfile not found at $BUILD_DIR/Dockerfile"
        exit 1
    fi
    
    # Prepare package list for Docker build
    if [[ -n "$ONLY_PACKAGES" ]]; then
        print_msg "$YELLOW" "  -> Filtering packages: $ONLY_PACKAGES"
        
        # Create temporary filtered list
        > "$BUILD_DIR/packages"
        
        # Check each package against the main list
        for pkg in $ONLY_PACKAGES; do
            # Check if in package list (handle options like skip-pgp)
            if [[ -f "$REPO_DIR/packages" ]]; then
                grep "^$pkg\( \|$\)" "$REPO_DIR/packages" >> "$BUILD_DIR/packages" && {
                    print_msg "$GREEN" "    -> $pkg"
                } || {
                    print_msg "$YELLOW" "    -> $pkg (not found in package list)"
                }
            fi
        done
    else
        # Copy full packages list to build directory
        cp "$REPO_DIR/packages" "$BUILD_DIR/packages"
    fi
    
    # Build image
    cd "$BUILD_DIR"
    docker build -t omarchy-builder . || {
        print_msg "$RED" "Failed to build Docker image"
        exit 1
    }
    
    print_msg "$GREEN" "  -> Docker image built successfully!"
}

# Function to run build in Docker
run_docker_build() {
    print_msg "$BLUE" "==> Running package build in Docker..."
    
    # Create src directory if it doesn't exist
    mkdir -p "$REPO_DIR/src"
    
    # Build docker run command with options
    DOCKER_ENV=""
    if [[ "$SKIP_PGP" == true ]]; then
        print_msg "$YELLOW" "  -> Skipping PGP signature verification"
        DOCKER_ENV="$DOCKER_ENV -e SKIP_PGP=true"
    fi
    if [[ "$FORCE_REBUILD" == true ]]; then
        print_msg "$YELLOW" "  -> Forcing rebuild of all packages"
        DOCKER_ENV="$DOCKER_ENV -e FORCE_REBUILD=true"
    fi
    
    docker run --rm \
        $DOCKER_ENV \
        -v "$ARCH_DIR:/output" \
        -v "$ARCH_DIR:/var/cache/pacman/pkg" \
        -v "$REPO_DIR/src:/src" \
        omarchy-builder || {
        print_msg "$RED" "Docker build failed"
        exit 1
    }
    
    print_msg "$GREEN" "  -> Package build complete!"
}

# Function to clean Docker resources
clean_docker() {
    print_msg "$BLUE" "==> Cleaning Docker resources..."
    
    # Remove image
    docker rmi omarchy-builder 2>/dev/null || true
    
    # Clean temporary packages file from build directory
    rm -f "$BUILD_DIR/packages"
    
    print_msg "$GREEN" "  -> Cleanup complete!"
}

# Main execution
main() {
    print_msg "$BLUE" "================================"
    print_msg "$BLUE" "Omarchy Repository Docker Builder"
    print_msg "$BLUE" "================================"
    
    # Check for Docker
    if ! command -v docker &> /dev/null; then
        print_msg "$RED" "Error: Docker is not installed"
        print_msg "$YELLOW" "Please install Docker first:"
        print_msg "$YELLOW" "  sudo pacman -S docker"
        print_msg "$YELLOW" "  sudo systemctl start docker"
        print_msg "$YELLOW" "  sudo usermod -aG docker $USER"
        exit 1
    fi
    
    # Check if Docker daemon is running
    if ! docker info &> /dev/null; then
        print_msg "$RED" "Error: Docker daemon is not running"
        print_msg "$YELLOW" "Start Docker with: sudo systemctl start docker"
        exit 1
    fi
    
    # Parse command line arguments
    CLEAN_ONLY=false
    KEEP_IMAGE=false
    ONLY_PACKAGES=""
    SKIP_PGP=false
    FORCE_REBUILD=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --clean)
                CLEAN_ONLY=true
                shift
                ;;
            --keep-image)
                KEEP_IMAGE=true
                shift
                ;;
            --only)
                ONLY_PACKAGES="$2"
                shift 2
                ;;
            --skip-pgp)
                SKIP_PGP=true
                shift
                ;;
            --force)
                FORCE_REBUILD=true
                shift
                ;;
            -h|--help)
                echo "Usage: $0 [OPTIONS]"
                echo ""
                echo "Options:"
                echo "  --clean       Clean Docker resources only"
                echo "  --keep-image  Keep Docker image after build"
                echo "  --only \"pkg1 pkg2\"  Only build specific packages"
                echo "  --skip-pgp    Skip PGP signature verification"
                echo "  --force       Force rebuild even if no updates"
                echo "  -h, --help    Show this help message"
                echo ""
                echo "Examples:"
                echo "  $0                          # Build all packages"
                echo "  $0 --only \"yay walker-bin\"  # Only build yay and walker-bin"
                echo "  $0 --skip-pgp               # Build without PGP checks"
                echo ""
                echo "This script builds all packages listed in:"
                echo "  - packages.official (downloaded from Arch repos)"
                echo "  - packages.aur (built from AUR)"
                echo ""
                echo "All builds happen inside a Docker container."
                echo "No packages are installed on your host system."
                exit 0
                ;;
            *)
                print_msg "$RED" "Unknown option: $1"
                exit 1
                ;;
        esac
    done
    
    # Execute based on options
    if [[ "$CLEAN_ONLY" == true ]]; then
        clean_docker
    else
        # Build packages
        build_docker_image
        run_docker_build
        
        # Clean up unless keeping image
        if [[ "$KEEP_IMAGE" != true ]]; then
            clean_docker
        else
            print_msg "$YELLOW" "Docker image kept: omarchy-builder"
            print_msg "$YELLOW" "Remove with: docker rmi omarchy-builder"
        fi
        
        # Show results
        print_msg "$BLUE" "\n==> Build Summary:"
        local count=$(ls -1 "$ARCH_DIR"/*.pkg.tar.* 2>/dev/null | wc -l)
        if [[ $count -gt 0 ]]; then
            print_msg "$GREEN" "  -> Built/downloaded $count package(s)"
            print_msg "$GREEN" "  -> Packages are in: $ARCH_DIR"
            print_msg "$YELLOW" "\nNext step: Run ./scripts/update-repo.sh"
        else
            print_msg "$YELLOW" "  -> No packages were built"
            print_msg "$YELLOW" "  -> Check your package lists"
        fi
    fi
}

# Run main function
main "$@"