#!/usr/bin/perl -w

my $all = shift;

use POSIX qw(ctime mktime strftime);

sub count_revisions {
    my ($repo, $after, $before, $all) = @_;
    my @heads;
    if ($all) {
        @heads = `git --git-dir $repo show-ref --heads --hash`;
        chomp @heads;
    } else {
        @heads = 'HEAD';
    }
    # Yes, I know I can do this with git rev-list but this one is easier to
    # debug:
    my @command = ('git', '--git-dir', $repo , 'log', '--format=oneline',
                   '--after', $after, '--before', $before, @heads);
    # print "\n@command\n";
    open my $fh, '-|', @command
        or die "Can't start @command";
    my $count = 0;
    ++$count while <$fh>;
    close $fh
        or die "Can't stop @command";
    $count;
}

# This is a hack :-)
my $sum;
my @repos = (qw(MoarVM nqp rakudo roast), sub { $sum }, qw(perl parrot main));
my %map = (perl => 'perl 5', main => 'Iron*');
print "        ";
foreach my $name (@repos) {
    $name = '(sum)'
        if ref $name;
    printf "%8s", $map{$name} ? $map{$name} : $name;
}
print "\n";

my $now = time;

foreach my $year (2013, 2012) {
    foreach my $mon (reverse 1..12) {
        my $before_t = mktime(0, 0, 0, 1, $mon, $year - 1900);
        # Is the end of the time range in the future?
        next
            if $before_t > $now;
        my $before = ctime($before_t);
        my $after = ctime(mktime(0, 0, 0, 1, $mon -1, $year - 1900));

        $sum = 0;
        print strftime("%b %Y", 0, 0, 0, 1, $mon - 1, $year - 1900);
        foreach my $repo (qw(MoarVM nqp rakudo roast), sub { $sum },
                          qw(perl parrot main)) {
            my $count;
            if (ref $repo) {
                $count = $repo->();
            } else {
                $count = count_revisions("$repo.git", $after, $before, $all);
                $sum += $count;
            }
            printf "%8d", $count;
        }
        print "\n";
    }
}
