#!/bin/bash

# Check if the directory is provided as an argument
if [ -z "$1" ]; then
  echo "Usage: $0 <directory>"
  exit 1
fi

# Get the directory from the first argument
DIRECTORY=$1

# Check if the provided argument is a directory
if [ ! -d "$DIRECTORY" ]; then
  echo "Error: $DIRECTORY is not a valid directory."
  exit 1
fi

# Recursively iterate over files in the directory
find "$DIRECTORY" -type f | while read -r filepath; do
  # Check if the file is an image
  file_type=$(file --mime-type -b "$filepath")
  if [[ $file_type == image/* ]]; then
    # Apply the magick convert command with -trim option
    magick convert "$filepath" -trim "$filepath"
    echo "Processed: $filepath"
  else
    echo "Skipped (not an image): $filepath"
  fi
done

echo "All files processed."