#!/bin/bash

mkdir -p ~/auto-crop-pdf-program


# figure out the name of the Zebra printer
 
for i in `lpstat -e`; do  lpoptions -p $i | grep ZPL > /dev/null; if [ $? -eq 0 ]; then printer_name=$i; fi ;done

# Ask the user if they want to trim the white space and print the PDF

zenity --question --width=300 --height=100 --text="Looking to print a manually created PayPal shipping label with your thermal label printer? Select no to view the PDF in the systems default PDF viewer." 

if [ $? -eq 0 ]
then
	# copy the file to a place that a snap package can access
	cp "$1" ~/auto-crop-pdf-program/zebra-tmp-file.pdf

	# try this first, but options have changed so it may fail on some distributions or releases
	krop  --go --trim-padding 20 --trim --trim-use=all ~/auto-crop-pdf-program/zebra-tmp-file.pdf  -o ~/auto-crop-pdf-program/zebra-trim-file.pdf

	# if krop fails assume it's a version difference and utilize a different set of options (program has renamed the options we use)
	if  [ $? -ne 0 ]
	then
	        krop  --go --autotrim-padding 20 --autotrim ~/auto-crop-pdf-program/zebra-tmp-file.pdf  -o ~/auto-crop-pdf-program/zebra-trim-file.pdf  
	fi

	lp -d $printer_name -o fit-to-page -o media=Custom.4x6in ~/auto-crop-pdf-program/zebra-trim-file.pdf

	rm ~/auto-crop-pdf-program/zebra-tmp-file.pdf
	rm ~/auto-crop-pdf-program/zebra-trim-file.pdf
else
	# just open the pdf using the default pdf viewer
	xdg-open $1
fi
