#!/bin/sh
#
# Copyright (c) Josef "Jeff" Sipek, 2007
#

DO_NOT_CHECK_BRANCH_EXISTENCE=1

USAGE="[-n] [--in-reply-to <msgid>] [<hash> | <since>..[<until>] | ..<until>]"
. `dirname $0`/guilt

TMP_FILE=`get_tmp_file file`

while [ $# -gt 0 ]; do
	case "$1" in
		-n)
			do_not_send=t
			;;
		--in-reply-to)
			reply_to="$2"
			shift
			;;
		*)
			break
			;;
	esac
	shift
done

r=`munge_hash_range "$1"`
if [ $? -ne 0 ]; then
	usage
fi

# display the list of commits to be sent as patches
git-log --pretty=oneline "$r" | cut -c 1-8,41- | $pager

echo -n "Are these what you want to send? [Y/n] "
read n
if [ "$n" = "n" ] || [ "$n" = "N" ]; then
	die "Aborting..."
fi

dir=/tmp/patches-$RANDOM/
if [ -e $dir ]; then
	die "Conspiracy uncovered: Temporary dir '$dir' already exists"
fi
echo "Using '$dir' as temporary directory"

git-format-patch -o $dir -n -s "$r"

# get the to/cc addresses
echo -n "Enter all the To: email addresses (separated by space): "
read rawto
echo -n "Enter all the Cc: email addresses (separated by space): "
read rawcc

# convert list of email addresses to command line options
to_opts=""
for rt in $rawto; do
	to_opts="$to_opts --to $rt"
done
for rc in $rawcc; do
	to_opts="$to_opts --cc $rc"
done

opts=""

# more than 1 commit
if [ `git-rev-list "$r" | wc -l` -gt 1 ]; then
	opts="$opts --no-chain-reply-to --compose"
fi
opts="$opts $to_opts"

ls "$dir" | while read n; do
	fulln="$dir/$n"

	do_get_full_header "$fulln" | awk '
BEGIN{p=0}
/^$/{p=1}
/^[Cc][Cc]: / && (p==1){print substr($0, 5)}
' | sed -n -e '
1 h
2,$ H
$ {
	x
	s/\n/, /g
	p
}' > "$TMP_FILE"
	if [ -s "$TMP_FILE" ]; then
		head -1 "$fulln" > "$fulln~"
		echo -n "Cc: " >> "$fulln~"
		cat "$TMP_FILE" >> "$fulln~"
		tail -n +2 "$fulln" >> "$fulln~"
		mv "$fulln~" "$fulln"
		echo "${n:0:4}: Including Cc from patch description"
		rm -f "$TMP_FILE"
	fi
done

# last possible point to abort!
echo -n "Proceed with patchbomb (this is the last chance to abort)? [y/N] "
read n
if [ "$n" != "y" ] && [ "$n" != "Y" ]; then
	die "Aborting..."
fi

# ...and off they go.
cmd="git-send-email"
if [ ! -z "$do_not_send" ]; then
	echo "-n passed: not sending, command that would be executed:" >&2
	cmd="echo git-send-email"
fi

if [ -z "$reply_to" ]; then
	$cmd $opts $dir
else
	$cmd --in-reply-to "$reply_to" $opts $dir
fi

# cleanup?
echo -n "Delete temporary directory? [Y/n] "
read n

[ "$n" = "n" ] || [ "$n" = "N" ] && exit 0
rm -rf $dir
