#!/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}

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

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

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

case "$1" in
	--flush|-f)
		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
	;;
	--list|-l)
		echo "Showing queued mails in ${QUEUEDIR}:"
		echo
			for i in ${QUEUEDIR}/* ; do
			echo "* <${i##*/}>"
			echo
			messageinfo "${i}"
			echo
		done
	;;
	--wipe|-w)
		echo "Removing mails in ${QUEUEDIR}:"
			for i in ${QUEUEDIR}/* ; do
			echo -e "\t${i##*/}"
			rm "${i}"
		done
	;;
	--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=$(tempfile)
		cat - > ${tmpfile}
		newname=$(messageid ${tmpfile})
		mv "${tmpfile}" "${QUEUEDIR}/${newname}"
	;;
esac

exit 0
