Hazel Monitored Folder to Combine PDFs

This is the script that worked for me:

## Config
## Feel free to change these if needed

# Dir name to search for base & added PDF files:
WORK_DIR_NAME="14 - WNB"

# Base PDF name:
BASE_PDF_NAME="Base.pdf"

# Base PDF template location (set full path here):
BASE_PDF_TEMPLATE_PATH=/Users/hlgdesktop/Documents/Base.pdf

### Main script

HAZELFILE="$1"
BASEPATH=$(dirname "$HAZELFILE")
DIRNAME=$(basename "$BASEPATH")

# Check if current PDF name is the same as base PDF (combined PDF moved back to work folder)
if [ "$(basename "$HAZELFILE")" = "$BASE_PDF_NAME" ]; then

	# Just exiting script without any work
	exit 0

fi


# Check if current PDF file is in correct folder
if [ "$DIRNAME" = "$WORK_DIR_NAME" ]; then

	# Check if base file is not present
	if [ ! -f "$BASEPATH/$BASE_PDF_NAME" ]; then

		# Copy template to base file or exit with error if copy failed for some reason
		cp "$BASE_PDF_TEMPLATE_PATH" "$BASEPATH/$BASE_PDF_NAME" || exit 1

	fi
	
	# Setting lock to be sure no other script instance tamper with same PDF
	while ! mkdir -p /tmp/lock_hazelscript 2>/dev/null; do
		LOCK_PID=$(cat /tmp/lock_hazelscript/pid)
		[ -f /tmp/lock_hazelscript/pid ] && ! kill -0 $LOCK_PID 2>/dev/null && rm -rf "/tmp/lock_hazelscript"
	done

	echo $$ > /tmp/lock_hazelscript/pid
	
	trap "rm -rf /tmp/lock_hazelscript" QUIT INT TERM EXIT

	"/System/Library/Automator/Combine PDF Pages.action/Contents/Resources/join.py" --output=/tmp/output.pdf "$BASEPATH/$BASE_PDF_NAME" "$HAZELFILE"

	# Moving merged file back to base PDF (overwriting it!!!)
	mv -f /tmp/output.pdf "$BASEPATH/$BASE_PDF_NAME"

	# Deleting PDF file which have triggered Hazel
	rm -f "$HAZELFILE"
		
	# Releasing previous lock
	rm -rf /tmp/lock_hazelscript
		
fi
1 Like