#!/usr/bin/env bash

# process mail enqueued by enqueue.sh
#
# a rip-off from msmtpq
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or (at
#  your option) any later version.
#
# Cobbled together by thb@documentfoundation.org
#

BASE_DIR=~/mail/outdir
# wait 5 minutes if offline
TIMEOUT=300

# sanity checks
which nm-online > /dev/null 2>&1 || {
    echo "You need nm-online for this!"
	exit 1
}
which msmtp > /dev/null 2>&1 || {
    echo "You need msmtp for this!"
	exit 1
}

while true; do
	if nm-online -t $TIMEOUT; then
		# we're online - process queue
		ls $BASE_DIR/queue/* 2>/dev/null | while read ctrl_file; do
			mail_file=`head -n 1 "$ctrl_file"`
			subject=`awk '/^Subject: / { print $0; exit }' "$BASE_DIR/mails/$mail_file"`
			msmtp $(tail --lines=+2 "$ctrl_file") < "$BASE_DIR/mails/$mail_file"  # the mail goes out the door
			RC=$?
			if [ $RC -eq 0 ]; then
				echo "\"$subject\" sent ($mail_file)."
				rm "$BASE_DIR/mails/$mail_file" "$ctrl_file"   # nuke the files
			else
				echo "\"$subject\" send failed ($mail_file)" \
					"msmtp rc = $RC" \
					'check this out ...'                       # bad news ...
			fi
		done

		# sleep a bit, before the next run
		echo "sleeping ..."
		sleep $TIMEOUT
	fi	
done
