#!/bin/sh
#
# Released under the terms of GPLv3 or at your option any later version.
# No warranties.
# Copyright 2008-2010 Enrico Tassi <gares@fettunta.org>
#
# lines beginning with a double '#' are considered the documentation
# of the hook, and should use the markdown syntax
#
## Mail on Failure
## ===============
##
## `mail-on-failure` is a simple `post-*` hook that sends mails to the user
## in case the synchronization failed, in the style of fetchmail's messages
## about authentication failures.
##
## When synchronization fails, `$USER` receives a mail with the following
## subject containing the logs of the synchronization:
##
##     [smd] sync with $endpoint failed
##
## When a subsequent synchronization attempt is successful, the `$USER` is
## notified with the following message:
##
##     [smd] sync with $endpoint succeeded
## 
## Note that the mail is sent with the `mail` command, thus local
## delivery has to be functional.

when="$1"
what="$2"
endpoint="$3"
status="$4"

SMD_ROOT=$HOME/.smd
HOOK_NAMESPACE=mail-on-failure

# if the file exists, the failure was already reported by email
HOOK_STATUS=$SMD_ROOT/hooks/$HOOK_NAMESPACE

# on failure we send the mail, and create HOOK_STATUS
if [ "$when" = "post" -a "$status" != 0 -a ! -f $HOOK_STATUS-$endpoint ]; then
	# something failed, we mail the $USER
	TMP=`mktemp`
	cat > $TMP <<-EOT
	There was an error while synchronizing with endpoint "$endpoint" 
	using smd-$what on `date`.  Logs follow:

	EOT

	echo "----------- client log --------------" >> $TMP
	cat $SMD_ROOT/log/client.$endpoint.log | tr -d '\015' >> $TMP
	echo >> $TMP
	echo "----------- server log --------------" >> $TMP
	cat $SMD_ROOT/log/server.$endpoint.log | tr -d '\015' >> $TMP
	echo >> $TMP
	echo "-- " >> $TMP
	echo "Sync Mail Dir - mail-on-failure hook" >> $TMP

	mail -s "[smd] sync with $endpoint failed" $USER < $TMP

	touch $HOOK_STATUS-$endpoint

	rm $TMP
fi

# on success, if HOOK_STATUS exists, we remove it and send an email
# to say it is now OK
if [ "$when" = "post" -a "$status" = 0 ]; then 
	if [ -f $HOOK_STATUS-$endpoint ]; then
		mail -s "[smd] sync with $endpoint succeeded" \
			$USER <<-EOT 
		smd-$what succesfully completed for endpoint "$endpoint".
		EOT
		rm -f $HOOK_STATUS-$endpoint
	fi
fi

# vim:set ft=sh:
