#!/bin/bash

echo "Running notify script: $@"

client="$1" ; shift
current="$1" ; shift
working="$1" ; shift
finishing="$1" ; shift
warnings="$1" ; shift
sendmail="$1" ; shift

while [ "$#" -gt 0 ] ; do
	case "$1" in
		Subject:*)
			w=""
			[ "$warnings" != "0" ] && w="($warnings warnings)"
			h="$1 $client $w"
			;;
		*) h="$1"
			;;
	esac
	if [ -z "$headers" ] ; then
		headers="$h"
	else
		headers=$(printf "%s\n%s\n" "$headers" "$h")
	fi
	shift
done

catcmd="gunzip -c"

# Look for a log to attach
[ -z "$log" -a -f "$working/log" ] && log="$working/log" && id=$(cat "$working"/timestamp) && catcmd="cat"
[ -z "$log" -a -f "$working/log.gz" ] && log="$working/log.gz" && id=$(cat "$working"/timestamp)
[ -z "$log" -a -f "$finishing/log" ] && log="$finishing/log" && id=$(cat "$finishing"/timestamp) && catcmd="cat"
[ -z "$log" -a -f "$finishing/log.gz" ] && log="$finishing/log.gz" && id=$(cat "$finishing"/timestamp)
[ -z "$log" -a -f "$current/log" ] && log="$current/log" && id=$(cat "$current"/timestamp) && catcmd="cat"
[ -z "$log" -a -f "$current/log.gz" ] && log="$current/log.gz" && id=$(cat "$current"/timestamp)

if [ -z "$log" ] ; then
  echo "$headers" && echo && echo "No log found to send in email" | $sendmail
else
  (echo "$headers" && echo && echo "$id" && echo && echo "$log:" && echo && ($catcmd "$log" 2>/dev/null || cat "$log")) | $sendmail
fi

exit 0
