#!/bin/bash

# Check if in a distrobox container
if command -v distrobox &>/dev/null; then
    distrobox enter -e "$0" "$@"
    exit $?
fi

# Ensure output directory exists
mkdir -p out

# Check if GNU Parallel is installed
if ! command -v parallel &>/dev/null; then
    echo "GNU Parallel is not installed. Please install it first."
    echo "On Ubuntu/Debian: sudo apt-get install parallel"
    echo "On Fedora: sudo dnf install parallel"
    echo "On macOS with Homebrew: brew install parallel"
    exit 1
fi

# Function to process a single image
process_image() {
    local input_file="$1"
    local output_file="out/$input_file"
    magick "$input_file" -auto-orient -quality 85% -resize 3000x1400\> \
           -interlace Plane -sampling-factor 4:2:0 \
           -define jpeg:dct-method=float -colorspace sRGB -strip "$output_file"
}

# Export the function so parallel can use it
export -f process_image

# Find all jpg files and process them in parallel
# Uses all available CPU cores by default
find . -maxdepth 1 -type f -name "*.jpg" | parallel --eta process_image {}

echo "Image processing complete!"
