#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  print [-d] [-q QUALITY] [FILE...]
		  print -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -d            print duplex/double-sided
		  -q QUALITY    choose the print quality, either:
		                low, medium (default) or high.
		  -h, --help    show this message

		  FILE          path to file to be printed


		Print FILE using CUPS using lp(1).


		Examples:

		  Print the given PostScript file with default quality:

		    $ print f1.ps


		  Print multiple PDF files with high quality:

		    $ print -dq high *.pdf


		  Print the file from STDIN, double-sided:

		    $ print -d < f2.ps


		  Print multiple source code files:

		    $ print src/*.{c,h}
	EOF
}

n_pages() {
	qpdf "$1" --show-npages
}

main() {
	if file -b "$FILE"   | grep -q PostScript; then
		ps2pdf "$FILE" "$NEWDIR"/in.pdf
	elif file -b "$FILE" | grep -q PDF; then
		cp "$FILE" "$NEWDIR"/in.pdf
	elif file -b "$FILE" | grep -q text; then
		enscript -C -o- "$FILE" | ps2pdf - "$NEWDIR"/in.pdf
	else
		lp $OPTS "$FILE"
		return
	fi
	cd "$NEWDIR"

	if [ -z "$DUPLEX" ]; then
		lp $OPTS in.pdf
		cd - > /dev/null
		return
	fi

	if [ "$(n_pages in.pdf)" = '1' ]; then
		lp $OPTS in.pdf
		return
	fi

	qpdf in.pdf --pages . 1-z:odd  -- odd.pdf
	qpdf in.pdf --pages . 1-z:even -- even.pdf

	NODD="$(n_pages  odd.pdf)"
	NEVEN="$(n_pages even.pdf)"

	printf 'Printing odd pages...\n' >&2
	lp $OPTS odd.pdf
	printf 'Has printing finished yet?  Once it does, reload the pages and hit it enter to continue. '
	read -r < /dev/tty
	lp $OPTS even.pdf

	if [ "$NODD" != "$NEVEN" ]; then
		printf '\n' | lp
	fi

	cd - > /dev/null
}

for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

DUPLEX=
OPTS='-o PrintQuality=standard'
while getopts 'dq:h' flag; do
	case "$flag" in
		(d)
			DUPLEX=1
			;;
		(q)
			case "$OPTARG" in
				low)
					OPTS='-o PrintQuality=draft'
					;;
				medium)
					OPTS='-o PrintQuality=standard'
					;;
				high)
					OPTS='-o PrintQuality=high'
					;;
				*)
					echo "Bad QUALITY option: \"$OPTARG\"" >&2
					exit 2
					;;
			esac
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

NEWDIR="$(mkdtemp)"
trap 'rm -rf "$NEWDIR"' EXIT
if [ -z "${1:-}" ]; then
	FILE="$NEWDIR"/STDIN
	cat - > "$FILE"
	main
else
	for f in "$@"; do
		FILE="$f"
		main
	done
fi
