#!/bin/sh
#
# ratio - pad images to a desired aspect ratio
# dependencies: imagemagick => magick(1) convert(1)
#
# ---
# source: https://patpatpat.xyz/data/ratio

usage() {
  printf '%s\n%s\n' "Usage: ratio [-b BACKGROUND] [-r WIDTH:HEIGHT] INPUT OUTPUT" \
    "see convert(1) for more details"
}

background=black
A=16
B=9

while getopts 'b:r:h?' arg; do
  case "${arg}" in
    b) background="${OPTARG}" ;;
    r)
      A=$(($(echo "${OPTARG}" | cut -d: -f1)))
      B=$(($(echo "${OPTARG}" | cut -d: -f2)))
      if [ "${A}" -le 0 ] || [ "${B}" -le 0 ]; then
        printf "Error: Invalid ratio '%s'\n" "${OPTARG}"
        exit 1
      fi
      ;;
    h)
      usage
      exit 0
      ;;
    \?)
      usage
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

if [ "$#" -ne 2 ]; then
  usage
  exit 1
fi

SIZE="$(identify "$1" | cut -d' ' -f3)"
W="$(echo "${SIZE}" | cut -dx -f1)"
H="$(echo "${SIZE}" | cut -dx -f2)"
X="$(((H + B - 1) / B))"
Y="$(((W + A - 1) / A))"

if [ "${Y}" -gt "${X}" ]; then
  X="${Y}"
fi

convert "$1" \
  -gravity center \
  -background "${background}" \
  -extent "$((X * A))x$((X * B))" \
  "$2"
