#!/usr/bin/perl -w

use Getopt::Std;
use Data::Dumper;

my ($opt_l);
&getopts("l");

open GNUPLOT, "|gnuplot -persist";
$data = "/tmp/commit-graph-$$.dat";
print "Using file $data\n";
open DATA, ">$data";
use FileHandle;
GNUPLOT->autoflush(1);
print GNUPLOT <<EOF;
set xdata time
set timefmt "%s"
set format x "%y/%m/%d" 
set xlabel "Date"
set grid
set key left top
EOF

open MAILMAP,`git rev-parse --show-cdup`.".mailmap";
@mailmap = <MAILMAP>;

# Determin which authors commited something
@author_list = `git log --pretty=format:"%an <%ae>" @ARGV|sort -u`;
%emails = {};

sub add_author
{
    ($author, $email) = @_;
    
    if (!defined $emails{$2}) {
	$authors{$1}{$2}=1;
	$emails{$2} = $1;
    }
}


foreach $a(@author_list) {
    chomp $a;
    ($an, $ae) = $a =~ /(.*) <(.*)>/;
    local $mailmapped;
    $mailmapped = 0;

    foreach (@mailmap) {
	if (/\s*([^<]*) <(.*)>\s*$/) {
	    if ($2 eq $ae) {
		add_author($1, $2);
		$mailmapped = 1;
	    }
	} else {
	    print STDERR "Unhandled mailmap line: $_\n";
	}
    }
    add_author($an, $ae) unless $mailmapped;
}
#print Dumper({%authors});

foreach $author(sort keys %authors) {
     @emails = keys %{ $authors{$author} };
     $email_re = '\('.join('\|', @emails).'\)';

     $cmd = qq/git log --pretty=format:"commit %ct %s" --author='$email_re' --no-merges --reverse --numstat @ARGV/;
	print "$cmd\n";
	@log = `$cmd`;
	$num_commits = 0;
	$added_lines = 0;
	foreach (@log) {
	    chomp;
	    if (/^commit (\d+)/) { $time=$1; $num_commits++; $printed=0; }
	    elsif (/(\d+)\s+(\d+)/) {
		$added_lines += $1;
	    } elsif (!$_) {
		print DATA "$time $num_commits $added_lines\n";
		$printed=1;
	    }
	}
	if ($num_commits > 0) {
	    if (!$printed) {
		print DATA "$time $num_commits $added_lines\n";
	    }
	    print DATA "\n\n";
	} else {
	    delete $authors{$author};
	}
}

if (!$opt_l) {
    @plots = ();
    $i=0;
    foreach $author(sort keys %authors) {
	push @plots, qq/"$data" index $i using 1:2 with linespoints title "$author"/;
	$i++;
    }
    print GNUPLOT "set ylabel \"Number of commits\"\n";
    print GNUPLOT "plot ", join(", ", @plots), ";\n";
} else {
    @plots = ();
    $i=0;
    foreach $author(sort keys %authors) {
	push @plots, qq/"$data" index $i using 1:3 with linespoints title "$author"/;
	$i++;
    }
    print GNUPLOT "set ylabel \"Added lines\"\n";
    # print GNUPLOT "set logscale y\n";
    print GNUPLOT "plot ", join(", ", @plots), ";\n";
}
