#!/usr/bin/perl
# Abhijit Menon-Sen <ams@toroid.org>

use Net::Jabber;

my $repo = "foo.git";

my $JID = 'foo@example.org';
my $password = "cd2e1f7d4a8500f394771b620a85aa5e";

# git config hooks.notify.branches 'master next'
# git config hooks.notify.recipients 'a@example.org b@example.org'

my @branches =
    split /,*\s+/, qx(git config hooks.notify.branches);

my @recipients =
    split /,*\s+/, qx(git config hooks.notify.recipients);

my $branches = join( "|", @branches ) || "master";

# Read "oldsha1 newsha1 refname" lines from stdin and convert the
# relevant ones into summary messages.

my @changes;
while ( <> ) {
    chomp;
    my ( $old, $new, $ref ) = split / /;

    $ref =~ s!refs/heads/!!;
    next unless $ref =~ /$branches/;

    my $s = qx(git log --no-merges --reverse --find-copies-harder --raw -r $old..$new);
    $s =~ s/^:.*?\t/\t/gsm;
    push @changes, [ $ref, $s ];
}

exit unless @changes;
exit unless @recipients;

# Send the notification messages to each recipient.

my ( $username, $hostname ) = split /@/, $JID;

my $client = new Net::Jabber::Client ();
$client->Connect( hostname => $hostname, srv => '_xmpp-client._tcp' )
    or die "Cannot connect to jabber server for $hostname: $!\n";

my @r = $client->AuthSend(
    username => $username,
    password => $password,
    resource => $repo
);
die "Cannot authenticate as $JID (@r)\n" if $r[0] ne "ok";

foreach my $c ( @changes ) {
    my ( $ref, $s ) = @$c;
    for my $r ( @recipients ) {
        my $msg = new Net::Jabber::Message ();
        $msg->SetMessage(
            to => $r,
            subject => "Changes pushed to branch $repo/$ref",
            body => $s
        );
        $client->Send( $msg );
    }
}

$client->Disconnect();
