#!/usr/bin/perl

use strict;
use warnings;

# === update ===
# this is gitolite's update hook

# ----------------------------------------------------------------------------
#       find the rc file, then pull the libraries
# ----------------------------------------------------------------------------

BEGIN {
    # people with shell access should be allowed to bypass the update hook,
    # simply by setting an env var that the ssh "front door" will never set
    exit 0 if exists $ENV{GL_BYPASS_UPDATE_HOOK};

    die "ENV GL_RC not set\n" unless $ENV{GL_RC};
    die "ENV GL_BINDIR not set\n" unless $ENV{GL_BINDIR};
}

use lib $ENV{GL_BINDIR};
use gitolite_rc;
use gitolite qw(:DEFAULT %repos);

# ----------------------------------------------------------------------------
#       start...
# ----------------------------------------------------------------------------

my ($perm, $creator, $wild) = repo_rights($ENV{GL_REPO});
trace("update: repo_rights perm is $perm");
my $reported_repo = $ENV{GL_REPO} . ( $wild ? " ($wild)" : "" );

# arguments are as supplied to an update hook by git; man githooks
my ($ref, $oldsha, $newsha) = @ARGV;
my $merge_base = '0' x 40;
# compute a merge-base if both SHAs are non-0, else leave it as '0'x40
# (i.e., for branch create or delete, merge_base == '0'x40)
chomp($merge_base = `git merge-base $oldsha $newsha`)
    unless $oldsha eq '0' x 40
        or $newsha eq '0' x 40;

# att_acc == attempted access -- what are you trying to do?  (is it 'W' or '+'?)
my $att_acc = 'W';
# rewriting a tag is considered a rewind, in terms of permissions
$att_acc = '+' if $ref =~ m(refs/tags/) and $oldsha ne ('0' x 40);
# non-ff push to ref
# notice that ref delete looks like a rewind, as it should
$att_acc = '+' if $oldsha ne $merge_base;

# were any 'D' perms specified?  If they were, it means we have to separate
# deletes from rewinds, so if the new sha is all 0's, change the '+' to a 'D'
$att_acc = 'D' if ( $repos{$ENV{GL_REPO}}{DELETE_IS_D} or $repos{'@all'}{DELETE_IS_D} ) and $newsha eq '0' x 40;
# similarly C for create a branch
$att_acc = 'C' if ( $repos{$ENV{GL_REPO}}{CREATE_IS_C} or $repos{'@all'}{CREATE_IS_C} ) and $oldsha eq '0' x 40;

# and now "M" commits.  This presents a bit of a problem.  All the other
# accesses (W, +, C, D) were mutually exclusive in some sense.  Sure a W could
# be a C or a + could be a D but that's by design.  A merge commit, however,
# could still be any of the others (except a "D").

# so we have to *append* 'M' to $att_acc (if the repo has MERGE_CHECK in
# effect and this push contains a merge inside)
if ( $repos{ $ENV{GL_REPO} }{MERGE_CHECK} or $repos{'@all'}{MERGE_CHECK} ) {
    if ( $oldsha eq '0' x 40 or $newsha eq '0' x 40 ) {
        warn "ref create/delete ignored for purposes of merge-check\n";
    } else {
        $att_acc .= 'M' if `git rev-list -n 1 --merges $oldsha..$newsha` =~ /./;
    }
}

my @allowed_refs;
# @all repos: see comments in similar code in check_score
push @allowed_refs, @ { $repos{$ENV{GL_REPO}}{$ENV{GL_USER}} || [] };
push @allowed_refs, @ { $repos{'@all'}       {$ENV{GL_USER}} || [] };
push @allowed_refs, @ { $repos{$ENV{GL_REPO}}{'@all'} || [] };
push @allowed_refs, @ { $repos{'@all'}       {'@all'} || [] };

my $minscore = 10;

# check the first ref -- this is a real (git) ref, like refs/heads/master
my ($score, $txt)           = check_ref(\@allowed_refs, $ENV{GL_REPO}, $ref, $att_acc);
trace("update: score $score trying $att_acc on ref $ref");
my $log_refex = $txt;   # save this for printing in the log record
my $denymsg = $txt if $score < 10;

# collect virtual ref types, if any
my %virtreftypes;
for (map { $_->[1] } @allowed_refs) {
    $virtreftypes{$1}++ if m(^VR_([\w-]+)/);
}
trace("update: virt refs applicable: " . join(",", sort keys %virtreftypes)) if %virtreftypes;

# here's how scoring works:
# (1) computing minscore: minimum score is 10 * number of ref types
#   [ref types: there's exactly one "real" ref (refs/heads/master, etc), and
#   any number of "virt"ual refs.  For each ref type applicable to this
#   repo+user, add 10 to the minimum score]
# (2) computing total score: each rule specified a score (default 10 for
#   accept rules and 0 for deny rules.  The score for a reftype is the
#   minimum of the rules in that reftype.  The total score is the sum of the
#   scores of each reftype.  [example: 1 real ref, 20 NAME/ refs (20 files
#   were changed), is 2 reftypes so minscore is 20.  Actual score is whatever
#   the real ref returns + minimum(whatever the NAME/ refs return).

# find virtual refs
for my $vrt (sort keys %virtreftypes) {
    my $vscore;
    my $match_sub;

    my @refs = get_virt_refs($vrt, $ref, $oldsha, $newsha);
    # the first *may* be one of the following words, to indicate what sort of
    # matching the virtref is expecting
    if ( ($refs[0] || '') =~ m(^VR_$vrt/(regex|lesser|greater|IP)$) ) {
        # "regex" is the default; there's no sub for this
        $match_sub = \&match_lesser if ($1 eq 'lesser');
        $match_sub = \&match_greater if ($1 eq 'greater');
        $match_sub = \&match_IP  if ($1 eq 'IP');
        shift @refs;
    }

    # if there were no virtrefs to start with (for example, an empty commit),
    # then bumping minscore up causes problems, so bail out
    next unless @refs;
    # each reftype specified increases the min score by 10
    $minscore += 10;

    # allow only refs that match the $vrt, for efficiency
    my @allowed_vrefs = grep { $_->[1] =~ m(^VR_$vrt/) } @allowed_refs;
    for my $r (@refs) {
        my ($rscore, $txt)  = check_ref(\@allowed_vrefs, $ENV{GL_REPO}, $r,   $att_acc, $match_sub);
        # the score for each vref type is the minimum of the scores for the
        # refs of that type
        unless (defined($vscore) and $vscore < $rscore) {
            $vscore = $rscore;
            $denymsg ||= $txt if $rscore < 10;
        }
    }
    $score += $vscore || 0;
    trace("update: score $score after adding vscore $vscore using " . scalar(@refs) . " refs from $vrt");
}

die (($denymsg || "access DENIED.  Score $score < $minscore") . "\n") if $score < $minscore;

# if we came here, all the checks succeeded.  Check secondary hooks now.
# Secondary hooks do not participate in scoring, by the way!
$UPDATE_CHAINS_TO ||= 'hooks/update.secondary';
-x $UPDATE_CHAINS_TO and system ( $UPDATE_CHAINS_TO, @ARGV ) and die "$UPDATE_CHAINS_TO died\n";

# now log it and exit 0 so git can get on with it
log_it("", "$att_acc\t" .  substr($oldsha, 0, 14) . "\t" . substr($newsha, 0, 14) .
    "\t$reported_repo\t$ref\t$log_refex");

exit 0;
