#!/usr/bin/env bash

dpi=144
dpi=72 # default for /screen
opt=(
	# https://www.ghostscript.com/doc/current/VectorDevices.htm#distillerparams
	#
	# -dPDFSETTINGS=/screen lower quality, smaller size. (72 dpi)
	#
	# -dPDFSETTINGS=/ebook for better quality, but slightly larger pdfs. (150 dpi)
	#
	# -dPDFSETTINGS=/prepress output similar to Acrobat Distiller "Prepress
	# Optimized" setting (300 dpi)
	#
	# -dPDFSETTINGS=/printer selects output similar to the Acrobat Distiller
	# "Print Optimized" setting (300 dpi)
	#
	# -dPDFSETTINGS=/default selects output intended to be useful across a wide
	# variety of uses, possibly at the expense of a larger output file
 	-dCompatibilityLevel=1.3
 	-dPDFSETTINGS=/screen
 	-dEmbedAllFonts=true
 	-dSubsetFonts=true
 	-dColorImageDownsampleType=/Bicubic
 	-dColorImageResolution="$dpi"
 	-dGrayImageDownsampleType=/Bicubic
 	-dGrayImageResolution="$dpi"
 	-dMonoImageDownsampleType=/Bicubic
 	-dMonoImageResolution="$dpi"
)

for arg; do
	if [[ ! -f $arg ]]; then
		echo "error: '$arg' is not a file" >&2
		exit 1
	elif [[ $arg != *.@(pdf|PDF) ]]; then
		echo "error: '$arg' is not a PDF file" >&2
		exit 1
	fi
fi

for arg; do
	if [[ $arg == *.* ]]; then
		out=${arg%.*}_compressed.${arg##*.}
	else
		out=${arg}_compressed
	fi
	# -q
	echo "Converting '$arg' to '$out'..."
	gs -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite "${opt[@]}" -sOutputFile="$out" "$arg"
 	du -hs "$arg" "$out"
done
