#!/bin/bash
#
# version-20220724
# $1 is passed filename of PNG
# is used to convert FULL-PAGE images
# to US Letter-sized PDFs.
# Input must be either 850x1100 or 2550x3300
# Uses graphics magick for conversion

if [[ "$DISPLAY" && "$(which Xdialog 2>&1 | grep -v "which: no")" ]]; then
	dialog="Xdialog"
else
	dialog="dialog"
fi

pth=`dirname "$1"`
cd $pth
mv "$1" `echo $1 | tr ' ' '_' | tr A-Z a-z` 2>/dev/null
newfile=`echo "$1" | sed "s/\.png/\.pdf/g"`

w=`gm identify -format "%w" $1`
h=`gm identify -format "%h" $1`
VALUE=`zenity --scale --text="Output Quality" --value="90" --min-value="50" --max-value="100"`
if [ "$h" -gt "$w" ]; then
	if [[ "$w" = "850" || "$w" = "2550" ]]; then
		# Horizontal Layout
		if [ "$w" = "850" ]; then
			gm convert $1 -page 850x1100 -quality $VALUE $newfile
		else
			gm convert $1 -page 2550x3300 -quality $VALUE $newfile
		fi
	else
		$dialog --title "Incorrect Size" --msgbox "\nThis utility is to convert full-page images to US Letter-sized PDFs.\nInput size must be -> 850x1100 or 2550x3300.\n" 0 0
	fi
	
else	

	if [[ "$w" = "1100" || "$w" = "3300" ]]; then
		# Horizontal Layout
		if [ "$w" = "1100" ]; then
			gm convert $1 -page 1100x850 -quality $VALUE $newfile
		else
			gm convert $1 -page 3300x2550 -quality $VALUE $newfile
		fi
	else
		$dialog --title "Incorrect Size" --msgbox "\nThis utility is to convert full-page images to US Letter-sized PDFs.\nInput size must be -> 850x1100 or 2550x3300.\n" 0 0
	fi	
fi

