#!/usr/bin/perl -w

use strict;
use Getopt::Std;
use File::Basename qw(basename dirname);

our ($opt_h, $opt_n, $opt_s);
getopts('hns');

$opt_h && usage();

sub usage {
	print STDERR "Usage: ${\basename $0} [-h] [-n] [-s] < <log_data>\n";
        exit(1);
}

my (%map);

sub mergelog_entry($$) {
	my ($name, $desc) = @_;
	my $key = $name;

	# store description in array, in email->{desc list} map
	if (exists $map{$key}) {
		# grab ref
		my $obj = $map{$key};

		# add desc to array
		push(@$obj, $desc);
	} else {
		# create new array, containing 1 item
		my @arr = ($desc);

		# store ref to array
		$map{$key} = \@arr;
	}
}

# sort comparison function
sub by_name($$) {
	my ($a, $b) = @_;

	uc($a) cmp uc($b);
}
sub by_nbentries($$) {
	my ($a, $b) = @_;
	my $a_entries = $map{$a};
	my $b_entries = $map{$b};

	@$b_entries - @$a_entries || by_name $a, $b;
}

my $sort_method = $opt_n ? \&by_nbentries : \&by_name;

sub summary_output {
	my ($obj, $num, $key);

	foreach $key (sort $sort_method keys %map) {
		$obj = $map{$key};
		$num = @$obj;
		printf "%s: %u\n", $key, $num;
	}
}

sub shortlog_output {
	my ($obj, $num, $key, $desc);

	foreach $key (sort $sort_method keys %map) {
		$obj = $map{$key};
		$num = @$obj;

		# output author
		printf "%s (%u):\n", $key, $num;

		# output author's 1-line summaries
		foreach $desc (reverse @$obj) {
			print "  $desc\n";
		}

		# blank line separating author from next author
		print "\n";
	}
}

sub changelog_input {
	my ($author, $desc);

	while (<>) {
		next unless /^    ((Pull)|(Merge)) (.*) from ([^\.:]*)/;
		$author = $5;
		$desc = $4;
		mergelog_entry($author, $desc);
	}
}

&changelog_input;
$opt_s ? &summary_output : &shortlog_output;
exit(0);
