#!/usr/bin/perl

use strict;
use File::Spec;
require "/home/data/common/eclipse.org-common-ldap.pl";

$ENV{PATH}     = '/usr/local/bin';
my $debug      = 0;

=doc
Based on contrib/hooks/update-paranoid by Shawn O. Pearce
Adapted by Denis Roy

Invoked as: update refname old-sha1 new-sha1

This script is run by git-receive-pack once for each ref that the
client is trying to modify.  If we exit with a non-zero exit value
then the update for that particular ref is denied, but updates for
other refs in the same run of receive-pack may still be allowed.

We are run after the objects have been uploaded, but before the
ref is actually modified.  We take advantage of that fact when we
look for "new" commits and tags (the new objects won't show up in
`rev-list --all`).

Unlike update-paranoid, this hook simply matches incoming
committer email addresses to the committer performing the
update.

Repository sections are matched on the basename of the repository
(after removing the .git suffix).

The opcode abbrevations are:

  C: create new ref
  D: delete existing ref
  U: fast-forward existing ref (no commit loss)
  R: rewind/rebase existing ref (commit loss)

if no opcodes are listed before the "for" keyword then "U" (for
fast-forward update only) is assumed as this is the most common
usage.

Refnames are matched by always assuming a prefix of "refs/".
This hook forbids pushing or deleting anything not under "refs/".

Refnames that start with ^ are Perl regular expressions, and the ^
is kept as part of the regexp.  \\ is needed to get just one \, so
\\d expands to \d in Perl.  The 3rd allow line above is an example.

Refnames that don't start with ^ but that end with / are prefix
matches (2nd allow line above); all other refnames are strict
equality matches (1st allow line).

Anything pushed to "heads/" (ok, really "refs/heads/") must be
a commit.  Tags are not permitted here.

Anything pushed to "tags/" (err, really "refs/tags/") must be an
annotated tag.  Commits, blobs, trees, etc. are not permitted here.
Annotated tag signatures aren't checked, nor are they required.

The special subrepository of 'info/new-commit-check' can
be created and used to allow users to push new commits and
tags from another local repository to this one, even if they
aren't the committer/tagger of those objects.  In a nut shell
the info/new-commit-check directory is a Git repository whose
objects/info/alternates file lists this repository and all other
possible sources, and whose refs subdirectory contains symlinks
to this repository's refs subdirectory, and to all other possible
sources refs subdirectories.  Yes, this means that you cannot
use packed-refs in those repositories as they won't be resolved
correctly.

=cut

my $git_dir = $ENV{GIT_DIR};
my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($git_dir); 
my $new_commit_check = "$git_dir/info/new-commit-check";
my $ref = $ARGV[0];
my $old = $ARGV[1];
my $new = $ARGV[2];
my $new_type;
my ($this_user) = getpwuid $<; # REAL_USER_ID
my $repository_name;
# my $current_committer_email;
my @allow_rules;
my @path_rules;
my %diff_cache;

# Make sure user is not wwwrun
# Bug 313945
if($this_user eq "wwwrun") {
        $this_user = $ENV{REMOTE_USER};
}

sub deny ($) {
	print STDERR "-Deny-    $_[0]\n" if $debug;
	print STDERR "\ndenied: $_[0]\n\n";
	exit 1;
}

sub grant ($) {
	print STDERR "-Grant-   $_[0]\n" if $debug;
	exit 0;
}

sub info ($) {
	print STDERR "-Info-    $_[0]\n" if $debug;
}

sub git_value (@) {
	open(T,'-|','git',@_); local $_ = <T>; chop; close T; $_;
}

sub ldap_group_check ($) {
        my $mesg = ldap_search ("ou=Group,dc=eclipse,dc=org","(&(gidNumber=$gid) (member=uid=$_,ou=People,dc=eclipse,dc=org))");
	info "Found: " . $mesg->count();
        return $mesg->count();
}

sub match_string ($$) {
	my ($acl_n, $ref) = @_;
	   ($acl_n eq $ref)
	|| ($acl_n =~ m,/$, && substr($ref,0,length $acl_n) eq $acl_n)
	|| ($acl_n =~ m,^\^, && $ref =~ m:$acl_n:);
}

sub all_new_committers () {
	local $ENV{GIT_DIR} = $git_dir;
	$ENV{GIT_DIR} = $new_commit_check if -d $new_commit_check;

	info "Getting committers of new commits in [$git_dir] .";
	info "new: $new";
	my %used;
	open(T,'-|','git','rev-list','--pretty=raw',$new,'--not','--all') or deny "Can't do this";
	while (<T>) {
		next unless s/^committer //;
		chop;
		s/^.*<//;
		s/>.*$//;
		info "Found $_." unless $used{$_}++;
	}
	close T;
	info "No new commits." unless %used;
	keys %used;
}

sub all_new_taggers () {
	my %exists;
	open(T,'-|','git','for-each-ref','--format=%(objectname)','refs/tags');
	while (<T>) {
		chop;
		$exists{$_} = 1;
	}
	close T;

	info "Getting taggers of new tags.";
	my %used;
	my $obj = $new;
	my $obj_type = $new_type;
	while ($obj_type eq 'tag') {
		last if $exists{$obj};
		$obj_type = '';
		open(T,'-|','git','cat-file','tag',$obj);
		while (<T>) {
			chop;
			if (/^object ([a-z0-9]{40})$/) {
				$obj = $1;
			} elsif (/^type (.+)$/) {
				$obj_type = $1;
			} elsif (s/^tagger //) {
				s/^.*<//;
				s/>.*$//;
				info "Found $_." unless $used{$_}++;
				last;
			}
		}
		close T;
	}
	info "No new tags." unless %used;
	keys %used;
}

sub check_committers (@) {
	my @bad;
	foreach (@_) { 
		$_ = lc($_);
		
		# commits can contain uid or mail
		# Convert email address to uid
		if ($_ =~ /\@/) {
			info "[$_] is an email address.  Converting.";
			my $mesg = ldap_search ("ou=People,dc=eclipse,dc=org", "(mail=$_)");
			if($mesg->count() gt 0) {
			        $_ = $mesg->entry(0)->get_value("uid");
				info "Obtained uid [$_]";
			}
		}

		info "Processing: [$_] to see if they are in group [$gid]";

		# lc($_) can be an email address or uid
		# perform ldap lookup to check if either of those is in $gid
		if(ldap_group_check($_) lt 1) {
			push @bad, $_;
		}
		

		# Old way:
		#if (lc($_) eq lc($current_committer_email) || lc($_) eq lc ($this_user)) {
			# do nothing, it is valid
		#}
		#else {
		#	push @bad, $_;
		#}
	}
	if (@bad) {
		print STDERR "\n";
		foreach (sort @bad) {
			print STDERR "error: git.eclipse.org does not know this committer,\n or this this committer cannot commit to this project (gid=$gid repo:$repository_name): $_.\n";
		}
		deny "You ($this_user) cannot push changes that were not committed by you or members of your project. Please fix your repository, and see http://wiki.eclipse.org/Git for information on configuring your Git environment.";
	}
}

sub load_diff ($) {
	my $base = shift;
	my $d = $diff_cache{$base};
	unless ($d) {
		local $/ = "\0";
		my %this_diff;
		if ($base =~ /^0{40}$/) {
			# Don't load the diff at all; we are making the
			# branch and have no base to compare to in this
			# case.  A file level ACL makes no sense in this
			# context.  Having an empty diff will allow the
			# branch creation.
			#
		} else {
			open(T,'-|','git','diff-tree',
				'-r','--name-status','-z',
				$base,$new) or return undef;
			while (<T>) {
				my $op = $_;
				chop $op;

				my $path = <T>;
				chop $path;

				$this_diff{$path} = $op;
			}
			close T or return undef;
		}
		$d = \%this_diff;
		$diff_cache{$base} = $d;
	}
	return $d;
}

deny "No GIT_DIR inherited from caller" unless $git_dir;
deny "Need a ref name" unless $ref;
deny "Refusing funny ref $ref" unless $ref =~ s,^refs/,,;
deny "Bad old value $old" unless $old =~ /^[a-z0-9]{40}$/;
deny "Bad new value $new" unless $new =~ /^[a-z0-9]{40}$/;
deny "Cannot determine who you are." unless $this_user;
grant "No change requested." if $old eq $new;

$repository_name = File::Spec->rel2abs($git_dir);
$repository_name =~ m,/([^/]+)(?:\.git|/\.git)$,;
$repository_name = $1;
info "Updating in '$repository_name'.";

my $op;
if    ($old =~ /^0{40}$/) { $op = 'C'; }
elsif ($new =~ /^0{40}$/) { $op = 'D'; }
else                      { $op = 'R'; }

# This is really an update (fast-forward) if the
# merge base of $old and $new is $old.
#
$op = 'U' if ($op eq 'R'
	&& $ref =~ m,^heads/,
	&& $old eq git_value('merge-base',$old,$new));

info "$this_user wants $op for $ref into [$git_dir]";

# We don't need pushing committer's mail address, since we check each commit individually
# See bug 374248
# Get current committer info
#{
#	my $mesg = ldap_search ("ou=People,dc=eclipse,dc=org","(uid=$this_user)");
#	$current_committer_email = $mesg->entry(0)->get_value("mail");
#}


if ($op ne 'D') {
	$new_type = git_value('cat-file','-t',$new);

#	if ($ref =~ m,^heads/,) {
#		deny "$ref must be a commit!" unless $new_type eq 'commit';
#	} elsif ($ref =~ m,^tags/,) {
#		deny "$ref must be an annotated tag." unless $new_type eq 'tag';
#	}

	check_committers (all_new_committers);
	check_committers (all_new_taggers) if $new_type eq 'tag';
}

close A;
grant "No hook rule has prevented the $op to $ref";
