#!/usr/bin/env bash
# ==========================================================================
#         ____            _                     _____           _
#        / ___| _   _ ___| |_ ___ _ __ ___     |_   _|__   ___ | |___
#        \___ \| | | / __| __/ _ \ '_ ` _ \ _____| |/ _ \ / _ \| / __|
#         ___) | |_| \__ \ ||  __/ | | | | |_____| | (_) | (_) | \__ \
#        |____/ \__, |___/\__\___|_| |_| |_|     |_|\___/ \___/|_|___/
#               |___/
#                             --- System-Tools ---
#                  https://www.nntb.no/~dreibh/system-tools/
# ==========================================================================
#
# GIMP Scripts
# Copyright (C) 2013-2026 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com

# Bash options:
set -eu


# ###### Handle arguments ###################################################
if [ $# -lt 3 ] ; then
   echo >&2 "Usage: $0 input output aspect|H:V|HxV|An [new_width]"
   exit 1
fi

inputFileName="$1"
outputFileName="$2"

inputImageSize=$(gm identify -format "%wx%h" "$inputFileName")

aspectArg="$3"
outputAspect=1
if [[ "$aspectArg" =~ ^([0-9]+\.{0,1}[0-9]*)([:x])([0-9]+\.{0,1}[0-9]*)$ ]] ; then
   outputAspect=$(LC_NUMERIC=C awk "BEGIN { print ${BASH_REMATCH[1]}/${BASH_REMATCH[3]} }")
else
   if [[ "$aspectArg" =~ ^([0-9]+\.{0,1}[0-9]*)$ ]] ; then
      outputAspect="${BASH_REMATCH[1]}"
   else
      if [[ "$aspectArg" =~ ^[Aa][0-9]$ ]] ; then
         outputAspect="1.414213562373"   # DIN A<n> is sqrt(2):1 in landscape format
      else
         echo >&2 "ERROR: Bad aspect specification: $aspectArg!"
         exit 1
      fi
   fi
fi

# shellcheck disable=SC2001
newWidth=$(echo "${inputImageSize}" | sed -e "s/x[0-9]*$//")
if [ $# -ge 4 ] ; then
   newWidth="$4"
   newHeight=$(LC_NUMERIC=C awk "BEGIN { print (${newWidth}/${outputAspect})+0.5 }")
fi


# ###### Load image #########################################################
# shellcheck disable=SC2001
inputWidth=$(echo "${inputImageSize}" | sed -e "s/x[0-9]*$//")
# shellcheck disable=SC2001
inputHeight=$(echo "${inputImageSize}" | sed -e "s/^[0-9]*x//")
inputAspect=$(LC_NUMERIC=C awk "BEGIN { print ${inputWidth}/${inputHeight} }")
if [[ "$inputAspect" =~ ^- ]] ; then
   inputAspect=$(LC_NUMERIC=C awk "BEGIN { print 1/${inputAspect} }")   # Input image is in portrait format => convert aspect
fi
# echo "Input: ${inputWidth}*${inputHeight} (${inputAspect})"


# ###### Crop image #########################################################
if [[ "$(LC_NUMERIC=C awk "BEGIN { print ${inputAspect}-${outputAspect} }")" =~ ^- ]] ; then   # inputAspect < outputAspect
   croppedInputWidth=${inputWidth}
   croppedInputHeight=$(LC_NUMERIC=C awk "BEGIN { print int(${croppedInputWidth}/${outputAspect})+0.5 }")
else
   croppedInputHeight=${inputHeight}
   croppedInputWidth=$(LC_NUMERIC=C awk "BEGIN { print int(${inputHeight}*${outputAspect})+0.5 }")
fi
cx=$(LC_NUMERIC=C awk "BEGIN { print int(${inputWidth}-${croppedInputWidth})/2+0.5 }")
cy=$(LC_NUMERIC=C awk "BEGIN { print int(${inputHeight}-${croppedInputHeight})/2+0.5 }")
# echo "Crop: ${croppedInputWidth}*${croppedInputHeight} [cx=${cx} cy=${cy}] (${outputAspect}:1)"


# ###### Resize image #######################################################
# if [ "${newWidth}" != "" ] ; then
#    echo "Resize: ${newWidth}*${newHeight} + (${outputAspect}:1)"
# fi

# ###### Run "convert" ######################################################
rm -f "${outputFileName}"
gm convert "$inputFileName" \
   -crop "${croppedInputWidth}"x"${croppedInputHeight}"+"${cx}"+"${cy}" \
   -resize "${newWidth}"x"${newHeight}" \
   +repage \
   "${outputFileName}"

# echo "Done!"

# gm identify "${outputFileName}"
