#!/bin/sh
# this script will eventually compress the resulting PS/PDF file and
# will attach it to a new message in Mail.app


ZIP=FALSE	# set to TRUE to let the PDF be zipped before
OWNER=$2	# who should own the zipped file

ZIPtheFile()
{
	# Look whether we should ZIP the file and return
	# appropriate file reference

	ZIPFile="$1"

	if [ ${ZIP} = "TRUE" ]; then
		zip -q -9 -j -D "$1".zip "$1"
		status=$?
		if [ ${status} = 0 ]; then
			/usr/sbin/chown ${OWNER}:${GROUP} "$1".zip
			chmod ${FILE_PERMS} "$1".zip
			# rm "$1"
			ZIPFile="$1".zip
		fi
	fi

	echo "${ZIPFile}"
			
}

# Look whether there exists a PDF (made by eg. GhostScript),
# call the ZIPtheFile function collect some accounting info
# and try to send the message with Mail.app

# check whether we should collect debug messages
if [ ${DEBUG} = TRUE ]; then
        exec 2>>${DEBUG_LOG}
else
        exec 2> /dev/null
fi

echo "$0 - Sending file with Mail.app" >&2

if [ -r "${TARGET_PDF}" ]; then
	ATTACHMENT=`ZIPtheFile "${TARGET_PDF}"`
else
	ATTACHMENT=`ZIPtheFile "${TARGET_FILE}"`
fi

CountOfPages=${CUPS_PrintSettingsPMTotalBeginPages}
if [ ${CountOfPages} -gt 1 ]; then
	CountOfPages="${CountOfPages} pages"
else
	CountOfPages="${CountOfPages} page"
fi

KBytes=`du -sk "${ATTACHMENT}" | cut -f1`

MailMsg="\r\r\\\"`basename "${ATTACHMENT}"`\\\" (${CountOfPages}, ${KBytes} kbytes) attached\r"

osascript <<-END-OF-APPLESCRIPT
	set theItem to (POSIX file "${ATTACHMENT}") as file
	tell application "Mail"
		set the new_message to (make new outgoing message with properties {visible:true,content:"${MailMsg}"})
		tell new_message
		set subject to "${CUPS_JobInfoPMJobName}"
		tell content to make new attachment with properties {file name:theItem} at after the last character
		end tell
		activate
	end tell
END-OF-APPLESCRIPT

exit 0

