#!/bin/bash

# Run in the current directory
SOURCE_DIR="$(pwd)"

# Loop over all JPEG files in current directory
find "$SOURCE_DIR" -maxdepth 1 -type f \( -iname "*.jpg" -o -iname "*.jpeg" \) | while read -r img; do
    filename=$(basename "$img")
    output="$SOURCE_DIR/$filename"  # overwrite in place

    # Get image dimensions
    read width height < <(identify -format "%w %h" "$img")

    # Determine longest side
    if [ "$width" -ge "$height" ]; then
        longest=$width
    else
        longest=$height
    fi

    # Resize only if longest side < 1600
    if [ "$longest" -lt 1600 ]; then
        # Resize proportionally, set longest side to 1600px
        convert "$img" -resize 1600x1600\> -strip -interlace JPEG -quality 85 "$output"
        echo "Resized and optimized: $filename"
    else
        # Just optimize without resizing
        convert "$img" -strip -interlace JPEG -quality 85 "$output"
        echo "Optimized without resize: $filename"
    fi

    # Delete original source if a separate file was created
    # (here output == img, so no need to delete, but if you used a temp file, you would remove it)
done
