#!/usr/bin/env bash
# Generate thumbnails using ImageMagick (magick)
# https://imagemagick.org/script/download.php
#
# Defaults to current directory creating thumbnails with 1000x1000
# dimensions and 200px white borders around the original image.
#
# Defaults can be overridden with ENV variables like this:
# $ THMB_BACKGROUND=black x-thumbgen ~/images/
#
# Created by: Ismo Vuorinen <https://github.com/ivuorinen> 2015

set -euo pipefail

# Default values
: "${THMB_SOURCE:=${1:-}}"
: "${THMB_BACKGROUND:=white}"
: "${THMB_RESIZE:=800x800}"
: "${THMB_EXTENT:=1000x1000}"

# Print usage information
usage()
{
  echo "Usage: $0 /full/path/to/image/folder"
  exit 1
}

# Check if ImageMagick is installed
check_magick_installed()
{
  if ! command -v magick &> /dev/null; then
    echo "magick not found in PATH, https://imagemagick.org/script/download.php"
    exit 1
  fi
}

# Generate thumbnails
generate_thumbnails()
{
  local source=$1

  magick \
    "${source}/*" \
    -resize "$THMB_RESIZE" \
    -background "$THMB_BACKGROUND" \
    -gravity center \
    -extent "$THMB_EXTENT" \
    -set filename:fname '%t_thumb.%e' +adjoin '%[filename:fname]'
}

# Main function
main()
{
  # Validate input
  if [ -z "$THMB_SOURCE" ]; then
    usage
  fi

  # Check if the source directory is valid
  if [ ! -d "$THMB_SOURCE" ]; then
    echo "Invalid directory: $THMB_SOURCE"
    exit 1
  fi

  check_magick_installed
  generate_thumbnails "$THMB_SOURCE"
}

main "$@"
