#!/bin/sh
#
# Submit a patch to any number of email-addresses, but without
# the cumbersome dependencies introduced by the git-send-email.
#
# Instead of applying the 8942 chars long RFC-exact regex to
# match recipients email addresses against, we're satisfied with
# a simple @ somewhere inside an argument and just assume that
# people won't try anything obviously stupid
#

function usage() {
	echo "Usage: git submit upstream@email.org <commit-ish> [<commit-ish>]"
	exit 1
}

function abort() {
	echo "Aborting."
	exit 0
}

email= com1= com2= patches=
while [ "$#" -gt 0 ]; do
	case "$1" in
	*@*)
		email="$email $1"
	;;
	*)
		if [ -f "$1" ]; then
			patches="$patches $1"
		elif [ "$com1" ]; then
			com2="$1"
		else
			com1="$1"
		fi
	;;
	esac
	shift
done

commits=0
if [ "$com1" ]; then
	if [ -z "$com2" ]; then
		com2="$com1"
		com1=HEAD
	fi

	commits=$(git rev-list $com1 ^$com2 | wc -l)
fi

[ $commits -eq 0 -a -z "$patches" ] && usage
# [ "$email" ] || git repo-config --get patch_email_address
[ "$email" ] || usage

[ $commits -gt 1 ] && opts=-n

for patch in $(git format-patch $opts $com2 $com1 | sed 's/^* //'); do
	patches="$patches $patch"
done

echo "Sending the following patches:"
sed -sn '1s/^Subject: //p' $patches
echo
echo -n "To these nice people: "
echo "$email" | sed -e 's/^ //' -e 's/ /, /g'
echo
echo "Press enter to continue, ctrl-c to abort."
read

for p in $patches; do
	subject=$(sed -n '1s/^Subject: //p' $p)
	echo "Sending $subject"
	sed 1d $p | mail -s "$subject" $email || abort
done
