#!/bin/bash
#
if [ $# -lt 2 ]; then
	echo usage: make-linus-pull tag from-sha
	exit
fi

who="Linus"
tag=$1
from_sha=$2

here=`dirname $0`

repo="git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-trace.git"

sha1=`git rev-list --max-count=1 $tag`

prolog=/tmp/prog-$tag

get_patch_count() {
	git log --pretty=oneline $from_sha..$tag |
			wc | awk '{print $1;}'
}

get_single_commit() {
	git log --pretty=oneline $from_sha..$tag |
			awk '{print $1;}'
}

print_tag_text() {
	echo
	git show $tag | perl -e '
	my $p = 0;
	while (<>) {
		last if (/^-----BEGIN PGP SIGNATURE-----$/);
		print if ($p);
		$p = 1 if (/^$/);
	}'
	echo
}

perl_shortlog() {
	perl -e '
my %commits;
my %counts;
my $name;
while (<>) {
	next if (/^\s*$/);

	if (/^(.*) \(1\):\s*$/) {
		$name = $1;
		if (defined($counts{$name})) {
			$counts{$name}++;
		} else {
			$counts{$name} = 1;
		}
		next;
	}
	$commits{$name} .= $_;
}

foreach $name (sort keys %counts) {
	print "$name ($counts{$name})\n";
	print "$commits{$name}\n";
}
'
}

get_emails() {
	git shortlog -e $from_sha..$tag |
		 perl -e '
my $first=1;
while (<>) {
	if (m,^(.*) \(\d+\):,) {
		next if ($1 =~ m/rostedt\@goodmis.org/);
		next if ($1 =~ m/Ingo Molnar/);
		print ", " if (!$first);
		print "$1";
		$first = 0;
	}
}'
}

get_shortlog() {
	git shortlog $from_sha..$tag
}	

get_diffstat() {
	git diff -M --stat --summary $from_sha $tag
}

get_diff() {
	git diff -M $from_sha $tag
}

do_prolog_header() {
	get_shortlog
	echo '----'
	get_diffstat
}

patches=`get_patch_count`

if [ $patches -eq 0 ]; then
	echo "no commits to process"
	exit
fi

# reset prolog
get_emails > $prolog
echo "" >> $prolog

tagsha1=`git show-ref -s --head $tag | tail -1`
head="Tag SHA1: $tagsha1
Head SHA1: $sha1"
body=`print_tag_text`

if [ -f ./notes ]; then
	notes=`cat ./notes`
else
	notes=''
fi

commit=`get_single_commit`

echo "making single patch in $prolog"

echo \
"
$who,
$body
$notes

Please pull the latest $tag tree, which can be found at:

" >> $prolog

echo \
"  $repo
$tag

$head

" >> $prolog

do_prolog_header >> $prolog
echo '---------------------------' >> $prolog
if [ $patches -eq 1 ]; then
	git show $commit >> $prolog
else
	get_diff >> $prolog
fi
