#!/usr/bin/env bash

##
# nbQUEUE adds queue support for nbsmtp
#
# To use nbQUEUE just create ${QUEUEDIR} and then set
#   nbqueue as your sendmail program. To flush the queue
#   (i.e. send all queued mails) just run nbqueue --flush.
##

shopt -s nullglob

QUEUEDIR=${QUEUEDIR:-~/.nbsmtp/.queue}
LOCKFILE=${QUEUEDIR}/.nbqueue.lock
LOCKSLEEPTIME=8
LOCKRETRIES=30

# This flag ensures that the queue lock is only removed
# by unlockq() if it was set by this nbqueue process.
# This is needed because unlockq() might be called
# asynchronously as a signal handler (see 'trap' below).
gotlock=0

if type lockfile >/dev/null 2>/dev/null ; then
	LOCKUTILITY=lockfile
elif type dotlockfile >/dev/null 2>/dev/null ; then
	LOCKUTILITY=dotlockfile
else
	unset LOCKUTILITY
fi

lockq() {
	[[ -n ${LOCKUTILITY} ]] || return

	case ${LOCKUTILITY} in
		lockfile) lockcmd="lockfile -${LOCKSLEEPTIME} -r ${LOCKRETRIES} ${LOCKFILE}" ;;
		dotlockfile) lockcmd="dotlockfile -r ${LOCKRETRIES} ${LOCKFILE}" ;;
	esac

	if ${lockcmd} ; then
		gotlock=1
	else
		echo "nbqueue[$$] - failed to lock queue"
		exit 1
	fi
}

unlockq() {
	[[ -n ${LOCKUTILITY} ]] && [[ ${gotlock} -eq 1 ]] || return

	case ${LOCKUTILITY} in
		lockfile) lockcmd="rm -f ${LOCKFILE}" ;;
		dotlockfile) lockcmd="dotlockfile -u ${LOCKFILE}" ;;
	esac

	gotlock=0
	${lockcmd} || echo "nbqueue[$$] - failed to unlock queue"
}

messageid() {
	sed -n -e '1,/^$/ {
		/^Message-[iI][dD]: *<\([^>]*\)>.*$/s//\1/p
	}' $1
}

messageinfo() {
	sed -n -e '1,/^$/ {
		/^Date: .*$/p
		/^From: .*$/p
		/^To: .*$/p
		/^[Bb]\{0,1\}[cC]\{2\}: .*$/p
		/^Subject: .*$/p
	}' $1
}

[[ -d "${QUEUEDIR}" ]] || mkdir -p "${QUEUEDIR}" || { 
	echo "${0}: ${QUEUEDIR} does not exist and I cannot create it"
	exit 1
}

trap "unlockq" SIGHUP SIGINT SIGTERM

case "$1" in
	--flush|-f)
		lockq
		for i in ${QUEUEDIR}/* ; do
			echo -n "Sending ${i}... "
			nbsmtp < "${i}"

			if [[ $? -eq 0 ]] ; then
				rm "${i}"
				echo "ok."
			else
				echo "failed, keeping message in queue."
			fi
		done
		unlockq
	;;
	--list|-l)
		echo "Showing queued mails in ${QUEUEDIR}:"
		echo
			for i in ${QUEUEDIR}/* ; do
			echo "* <${i##*/}>"
			echo
			messageinfo "${i}"
			echo
		done
	;;
	--wipe|-w)
		lockq
		echo "Removing mails in ${QUEUEDIR}:"
			for i in ${QUEUEDIR}/* ; do
			echo -e "\t${i##*/}"
			rm "${i}"
		done
		unlockq
	;;
	--help|-h)
		cat << EOH
nbQUEUE Copyright (C) 2005 Fernando J. Pereda
nbQUEUE is supplied with nbSMTP [ http://nbsmtp.ferdyx.org ]
nbQUEUE and nbSMTP are released under the GPLv2

${0##*/} [ action ]

Possible actions are:
	--flush | -f	- Send all mails in the queue
	--wipe  | -w	- Remove all mail in the queue
	--list  | -l	- List all messages in the queue
	--help  | -h	- Print this help message
EOH
			exit 0
	;;
	*)
		# Asume queue mode
		tmpfile=$(mktemp -q -t nbqueue.XXXXXX)
		cat - > ${tmpfile}
		newname=$(messageid ${tmpfile})
		lockq
		mv "${tmpfile}" "${QUEUEDIR}/${newname}"
		unlockq
	;;
esac

exit 0
