#!/bin/sh

echo "Running notify script: $@"

# Arguments specified by the burp binary come first.
# Normally, most of the following get set as you would expect.
# In the server_script_pre/post case, burp does not have a directory from
# which to read a log. In that case, it will set 'client' to the clientname,
# 'basedir' blank, and 'storagedir' to the log buffer.
client="$1" ; shift
basedir="$1" ; shift
storagedir="$1" ; shift
file="$1" ; shift
brv="$1" ; shift # one of backup/restore/verify
warnings="$1" ; shift

# Arguments given by the user in the conf files come next.
sendmail="$1" ; shift

working="$basedir/working"
finishing="$basedir/finishing"

while [ "$#" -gt 0 ] ; do
	case "$1" in
		Subject:*)
			w=""
			[ -n "$warnings" -a "$warnings" != "0" ] \
				&& w="($warnings warnings)"
			h="$1"
			h="${h//%c/$client}"
			h="${h//%w/$w}"
			h="${h//%b/$brv}"
			;;
		*) 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
if [ "$brv" = "backup" ] ; then
  [ -z "$log" -a -f "$working/$file" ] && \
    log="$working/$file" && id=$(cat "$working"/timestamp) && catcmd="cat"
  [ -z "$log" -a -f "$working/$file.gz" ] && \
    log="$working/$file.gz" && id=$(cat "$working"/timestamp)
  [ -z "$log" -a -f "$finishing/$file" ] && \
    log="$finishing/$file" && id=$(cat "$finishing"/timestamp) && catcmd="cat"
  [ -z "$log" -a -f "$finishing/$file.gz" ] && \
    log="$finishing/$file.gz" && id=$(cat "$finishing"/timestamp)
fi

[ -z "$log" -a -f "$storagedir/$file" ] && \
  log="$storagedir/$file" && id=$(cat "$storagedir"/timestamp) && catcmd="cat"
[ -z "$log" -a -f "$storagedir/$file.gz" ] && \
  log="$storagedir/$file.gz" && id=$(cat "$storagedir"/timestamp)

if [ -z "$log" -a -z "$basedir" -a -n "$storagedir" ] ; then
  # This is the case where burp has no log directory and has given a buffer to
  # log via the storagedir argument.
  (echo "$headers" && echo && echo "$storagedir") | $sendmail
elif [ -z "$log" ] ; then
  echo "$headers" && echo && echo "No log found to send in email" | $sendmail
else
  # The normal case.
  (echo "$headers" && echo && echo "$id" && echo && echo "$log:" && echo && ($catcmd "$log" 2>/dev/null || cat "$log")) | $sendmail
fi

exit 0
