#! /bin/bash

# usage:
# $1 mail to address
# $2 mail cc address (optional)

# Originally written by Andres Loeh
# Changed by Duncan Coutts to send an email per-patch rather than per-push

email=$1
[[ -n $2 ]] && emailcc="-c $2"

[[ -z ${DARCS} ]] && DARCS="/usr/local/bin/darcs"
[[ -z ${CURRENTHASH} ]] && CURRENTHASH=".current-hash"

Xtract() {
  /srv/code/yi/Xtract -n "$1" -;
}

hash=$(cat ${CURRENTHASH})

repo=$(/bin/pwd | sed 's|^/srv/code/||')

# no longer works with darcs2
# patches_url="http://code.haskell.org/yi/_darcs/patches/"

# find all the patches since the one identified by the current hash
patches=$(${DARCS} changes		\
	--reverse			\
	--from-match="hash ${hash}"	\
	--match="not hash ${hash}"	\
	--xml-output			\
	| Xtract "//patch/@hash" )

# update the current hash to the last hash we've seen.
patch=${patches##*[${IFS}[:cntrl:]]}
if [[ -n ${patch} ]]; then
	echo ${patch} > ${CURRENTHASH}
fi

# Send the emails asynchronously so we don't hold up the apply process
# This also allows the sending of the emails to take it's time and do
# them in the proper chronological order.
(
	# send an email for each patch
	for patch in ${patches}; do
	
	        # sleep for at least a second otherwise all the emails sent can have
		# the same timestamp and we loose the order of the patches.
		sleep 1.1
		
		patchname=$(${DARCS} changes		\
			--matches="hash ${patch}"	\
			--xml-output			\
			| Xtract "//patch[0]/name/-" )
		
		subject="patch applied (${repo}): ${patchname}"

		${DARCS} changes			\
			--matches="hash ${patch}"	\
			--summary			\
			| mutt -s "${subject/&amp;/&}" "${email}" "${emailcc}"
                # no longer works with darcs2
		# && echo -e "\nView patch online:\n\n  ${patches_url}${patch}") \
	done
) &

# return to darcs without waiting for the emails to finnish sending
exit 0

