#!/usr/bin/env bash

width=$(identify -ping -format "%w" "$1")
height=$(identify -ping -format "%h" "$1")
ICON=/usr/local/share/icons/custom/resize.png
IMAGE=/usr/local/share/icons/custom/resize-app.png

raw_options=$(yad --center --title "Image Resizer" --text="Resize the Selected Image with Imagemagick.\n*Note enlarging images will degrade quality!\nFor enlarging use the 'Image Upscale' Action." --width=600 --height=200 --border=24 --window-icon="$ICON" --image="$IMAGE" --form --float-precision 0 --field "Filename":RO --field "Width":NUM --field "Height":NUM --field "Preserve aspect ratio":CHK "$1" "$width" "$height" true)

# 0: Filename
# 1: Width
# 2: Height
# 3: Preserve aspect ratio?

options=()
while read -d "|" option; do
	options+=("$option")
done < <(echo "$raw_options")

newfilename=${options[0]%.*}.resized.${options[0]##*.}

echo ${options[0]} --\> ${newfilename}

if [[ "${options[3]}" == "TRUE" ]]; then
	echo Preserving aspect ratio.
	convert "${options[0]}" -colorspace RGB -resize ${options[1]}x${options[2]} -colorspace sRGB "${newfilename}"
else
	echo Not preserving aspect ratio.
	convert "${options[0]}" -colorspace RGB -resize ${options[1]}x${options[2]}! -colorspace sRGB "${newfilename}"
fi

new_width=$(identify -ping -format "%w" "${newfilename}")
new_height=$(identify -ping -format "%h" "${newfilename}")

echo ${width}x${height} --\> ${new_width}x${new_height}
