#!/usr/bin/env bash
#
# resize-image - create new image resized by the specified amount
# dependencies: imagemagick
#
# variables:
#   $1: path to the original image
#   $2: resize value (default is '50%')
#
# usage:
#     resize-image ./path/to/image.jpg 30%
#     resize-image ./path/to/image.jpg 1000x1000!
#
# ---
# see: https://imagemagick.org/script/command-line-processing.php#geometry

if ! command -v magick >/dev/null 2>&1; then
  printf '%s\n' "imagemagick command-line tool is not installed." >&2
  exit 1
fi

# check if file is an image file
mime="$(file -L -i -- "$1" | cut -d '/' -f 1)"

# strip file extension
extension="${1##*.}"

if ! echo "${mime}" | grep -q ':.*image' || [ "${extension}" = "gif" ]; then
  printf "'%s' is not an image file.\n" "$1"
  exit 1
fi

path="$(dirname "$1")"
filename="$(basename "$1")"
geometry="${2:-50%}"

magick \
  "$1" \
  -colorspace RGB \
  +sigmoidal-contrast 11.6933 \
  -define filter:filter=Sinc \
  -define filter:window=Jinc \
  -define filter:lobes=3 \
  -sigmoidal-contrast 11.6933 \
  -colorspace sRGB \
  -background transparent \
  -gravity center \
  -resize "${geometry}" \
  +append \
  "${path}/_${filename}" \
  && printf "* %s (%s)\n" \
    "${path}/_${filename}" \
    "${geometry}"
