#!/usr/bin/perl -w
#
# Copyright 2005 Alexandre Julliard
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.

use strict;
use open ':utf8';
use Encode 'encode';
use Cwd 'realpath';

binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';

sub git_config($);
sub get_repos_name();

# some parameters you may want to change

# set this to something that takes "-s"
my $mailer = "/usr/bin/mail";

# debug mode
my $debug = 0;

# configuration parameters

my $project_name = 'gstreamer';

# base URL of the gitweb repository browser
my $gitweb_url = "http://cgit.freedesktop.org/$project_name";


# default repository name
my $repos_name = get_repos_name();

# max size of diffs in bytes
my $max_diff_size = 10000;

# address for mail notices
my $commitlist_address = 'gstreamer-commits@lists.freedesktop.org';
#my $commitlist_address = 'tpm';

# max number of individual notices before falling back to a single global notice
my $max_individual_notices = 100;

# format an integer date + timezone as string
# algorithm taken from git's date.c
sub format_date($$)
{
    my ($time,$tz) = @_;

    if ($tz < 0)
    {
        my $minutes = (-$tz / 100) * 60 + (-$tz % 100);
        $time -= $minutes * 60;
    }
    else
    {
        my $minutes = ($tz / 100) * 60 + ($tz % 100);
        $time += $minutes * 60;
    }
    return gmtime($time) . sprintf " %+05d", $tz;
}

# fetch a parameter from the git config file
sub git_config($)
{
    my ($param) = @_;

    open CONFIG, "-|" or exec "git", "config", $param;
    my $ret = <CONFIG>;
    chomp $ret if $ret;
    close CONFIG or $ret = undef;
    return $ret;
}

# send an email notification
sub mail_notification($$$@)
{
    my ($name, $subject, $content_type, @text) = @_;
    $subject = encode("MIME-Q",$subject);
    if ($debug)
    {
        print "---------------------\n";
        print "To: $name\n";
        print "Subject: $subject\n";
        print "Content-Type: $content_type\n";
        print "\n", join("\n", @text), "\n";
    }
    else
    {
        my $pid = open MAIL, "|-";
        return unless defined $pid;
        if (!$pid)
        {
            exec $mailer, "-s", $subject, $name, or die "Cannot exec $mailer";
        }
        print MAIL join("\n", @text), "\n";
        close MAIL;
    }
}

# get the default repository name (includes subdirectory, if any)
sub get_repos_name()
{
    my $dir = `git rev-parse --git-dir`;
    chomp $dir;
    my $repos = realpath($dir);
    $repos =~ s/(.*?)((\.git\/)?\.git)$/$1/;
    $repos =~ s%(.*\/$project_name)/([^/]+/?[^/]*)/?$%$2%;
    return $repos;
}

# extract the information from a commit or tag object and return a hash containing the various fields
sub get_object_info($)
{
    my $obj = shift;
    my %info = ();
    my @log = ();
    my $do_log = 0;

    open TYPE, "-|" or exec "git", "cat-file", "-t", $obj or die "cannot run git-cat-file";
    my $type = <TYPE>;
    chomp $type;
    close TYPE;

    open OBJ, "-|" or exec "git", "cat-file", $type, $obj or die "cannot run git-cat-file";
    while (<OBJ>)
    {
        chomp;
        if ($do_log)
        {
            last if /^-----BEGIN PGP SIGNATURE-----/;
            push @log, $_;
        }
        elsif (/^(author|committer|tagger) ((.*)(<.*>)) (\d+) ([+-]\d+)$/)
        {
            $info{$1} = $2;
            $info{$1 . "_name"} = $3;
            $info{$1 . "_email"} = $4;
            $info{$1 . "_date"} = $5;
            $info{$1 . "_tz"} = $6;
        }
        elsif (/^tag (.*)$/)
        {
            $info{"tag"} = $1;
        }
        elsif (/^$/) { $do_log = 1; }
    }
    close OBJ;

    $info{"type"} = $type;
    $info{"log"} = \@log;
    return %info;
}

# send a commit notice to a mailing list
sub send_commit_notice($$)
{
    my ($ref,$obj) = @_;
    my %info = get_object_info($obj);
    my @notice = ();
    my $subject;

    printf "sending e-mail for $obj\n";

    # TODO normal tags are not identified
    if ($info{"type"} eq "tag")
    {
        push @notice,
        "Module: $repos_name",
        "Branch: $ref",
        "Tag:    $obj",
        $gitweb_url ? "URL:    $gitweb_url/tag/?id=$obj\n" : "",
        "Tagger: " . $info{"tagger"},
        "Date:   " . format_date($info{"tagger_date"},$info{"tagger_tz"}),
        "",
        join "\n", @{$info{"log"}};
        $subject = "Tag " . $info{"tag"} . ": " . ${$info{"log"}}[0];
    }
    else
    {
        push @notice,
        "Module: $repos_name",
        "Branch: $ref",
        "Commit: $obj",
        $gitweb_url ? "URL:    $gitweb_url/commit/?id=$obj\n" : "",
        "Author: " . $info{"author"},
        "Date:   " . format_date($info{"author_date"},$info{"author_tz"}),
        "",
        join "\n", @{$info{"log"}},
        "",
        "---",
        "";

        open STAT, "-|" or exec "git", "diff-tree", "--stat", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
        push @notice, join("", <STAT>);
        close STAT;

        open DIFF, "-|" or exec "git", "diff-tree", "-p", "-M", "--no-commit-id", $obj or die "cannot exec git-diff-tree";
        my $diff = join( "", <DIFF> );
        close DIFF;

        if (($max_diff_size == -1) || (length($diff) < $max_diff_size))
        {
            push @notice, $diff;
        }
        else
        {
            push @notice, "Diff:   $gitweb_url/diff/?id=$obj" if $gitweb_url;
        }

        if ($ref eq 'master')
        {
            $subject = $repos_name . ": " . ${$info{"log"}}[0];
        }
        else
        {
            $subject = "[$ref] " . $repos_name . ": " . ${$info{"log"}}[0];
        }
    }

    mail_notification($commitlist_address, $subject, "text/plain; charset=UTF-8", @notice);
}

# send a global commit notice when there are too many commits for individual mails
sub send_global_notice($$$)
{
    my ($ref, $old_sha1, $new_sha1) = @_;
    my @notice = ();

    open LIST, "-|" or exec "git", "rev-list", "--pretty", "^$old_sha1", "$new_sha1" or die "cannot exec git-rev-list";
    while (<LIST>)
    {
        chomp;
        s/^commit /URL:    $gitweb_url\/commit\/?id=/ if $gitweb_url;
        push @notice, $_;
    }
    close LIST;

    mail_notification($commitlist_address, "New commits on branch $ref", "text/plain; charset=UTF-8", @notice);
}

# send all the notices
sub send_all_notices($$$)
{
    my ($old_sha1, $new_sha1, $ref) = @_;

    $ref =~ s/^refs\/heads\///;

    if ($old_sha1 eq '0' x 40)  # new ref
    {
        send_commit_notice( $ref, $new_sha1 ) if $commitlist_address;
        return;
    }

    my @commits = ();

    open LIST, "-|" or exec "git", "rev-list", "--topo-order", "^$old_sha1", "$new_sha1" or die "cannot exec git-rev-list";
    while (<LIST>)
    {
        chomp;
        die "invalid commit $_" unless /^[0-9a-f]{40}$/;
        unshift @commits, $_;
    }
    close LIST;

    if (@commits > $max_individual_notices)
    {
        send_global_notice( $ref, $old_sha1, $new_sha1 ) if $commitlist_address;
        return;
    }

    foreach my $commit (@commits)
    {
        send_commit_notice( $ref, $commit ) if $commitlist_address;
    }
}

# append repository path to URL
$gitweb_url .= "/$repos_name" if $gitweb_url;

while (<>)
{
    chomp;
    if (/^([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/) { send_all_notices( $1, $2, $3 ); }
}

exit 0;
