#!/bin/bash
# Place this file at /usr/lib/cups/hp-virtual, chown root:root and chmod 0744.
# Set your printer name, username, and path of env-wrapper script here

PRINTERNAME="My_Printer"
USERNAME="myusername"
ENVWRAPPER="/path/to/env-wrapper"

if [[ $# -eq 0 ]]; then
	echo 'file hp-virtual:/ "HP Virtual Printer" "HP Virtual Printer"'
	exit 0
fi

JOBID="$1"
USER="$2"
TITLE="$3"
COPIES="$4"
OPTIONS="$5"

filename="$(mktemp /tmp/hp-virtual.XXXXXXXX.pdf)"
cat > "${filename}"

pagecount="$(pdfinfo "${filename}" | awk '/Pages:/ { print $2 }')"

lpargs=""
for opt in ${OPTIONS}; do
	lpargs="${lpargs} -o ${opt}"
done

if (( pagecount <= 1 )); then
	lp -s -d "${PRINTERNAME}" -t "${TITLE}" "${filename}"
	rm -f "${filename}"
	exit 0
fi
lp -s -d "${PRINTERNAME}" -t "${TITLE}-even" -o page-set=even -o orientation-requested=6 -o outputorder=reverse "${filename}"
sudo -u "${USERNAME}" -- "${ENVWRAPPER}" kdialog --yesno "Press OK when printing one side is finished."
if [[ $? -ne 0 ]]; then
	rm -f "${filename}"
	exit 0
fi
lp -s -d "${PRINTERNAME}" -t "${TITLE}-odd" -o page-set=odd "${filename}"

rm -f "${filename}"
