#!/bin/bash

# Specify the input directory
INPUT_DIR="../../assets/pics/gallery/centerpiece"

# Array of image extensions to process (excluding webp)
IMAGE_EXTENSIONS=("*.heic" "*.jpg" "*.jpeg" "*.png" "*.gif")

# Loop through each image extension
for ext in "${IMAGE_EXTENSIONS[@]}"; do
    # Find files matching the current extension
    for filename in $(find "$INPUT_DIR" -type f -name "$ext"); do
        # Determine the output file name based on the original extension
        case "$ext" in
            *.heic)
                CONVERTED_FILE="${filename%.heic}.webp"
                ;;
            *.jpg|*.jpeg)
                CONVERTED_FILE="${filename%.{jpg,jpeg}}.webp"
                ;;
            *.png)
                CONVERTED_FILE="${filename%.png}.webp"
                ;;
            *.gif)
                CONVERTED_FILE="${filename%.gif}.webp"
                ;;
            *) # Default case for unknown file types (if you add more later)
                echo "Unknown file type: $filename"
                continue # Skip to the next file
                ;;
        esac

        # Skip if already converted
        if [[ -f "$CONVERTED_FILE" ]]; then
            echo "Skipping $filename, already converted."
            continue
        fi

        # Convert to WEBP
        echo "Converting $filename to $CONVERTED_FILE..."
        convert "$filename" -quality 85 "$CONVERTED_FILE"

        # Verify conversion success
        if [[ -f "$CONVERTED_FILE" ]]; then
            # Create a blank text file (caption file)
            txt_file="${CONVERTED_FILE%.webp}.txt"
            echo -e "" > "$txt_file"
            echo "Successfully converted $filename to $CONVERTED_FILE and created ${txt_file}"

            # Delete the original file
            echo "Deleting original file: $filename"
            rm "$filename"

        else
            echo "Error converting $filename"
        fi
    done
done