#!/usr/bin/perl

use strict;
use warnings;

my $ssh = $ENV{SSH_CLIENT} or die "Only SSH allowed\n";
my $base = $ENV{GIT_DIR} or die "GIT hook ENV malfunction!\n";
my $acl = {};
my $log = {};
my $conf = `git config --list`;
while ($conf =~ s/^acl.(\w+)=(.*)$//m) {
    my $param = $1;
    my $keys = $2;
    foreach my $key (split /,/, $keys) {
        $acl->{$param}->{$key} = 1;
    }
}
while ($conf =~ s/^log.(\w+)=(.*)$//m) {
    $log->{$1} = $2;
}

my $KEY = $ENV{KEY} || "UNKNOWN";
warn localtime().": [$KEY] git-server: RUNNING PUSH ...\n";
# Cannot pass without writers access:
my $allowed = $acl->{writers}->{$KEY};
# Check for logfile:
if (my $file = $log->{logfile}) {
    if ($file =~ m{^[^/]}) {
        # Force start with a / for absolute patth
        $file = "$base/$file";
    }
    if ($file =~ m{^(.*)/[^/]+$}) {
        my $log_dir = $1;
        system mkdir => -p => $log_dir if !-d $log_dir;
        if (open my $fh, ">>", $file) {
            my ($ip) = split / /,$ssh;
            if ($allowed) {
                print $fh localtime().": [$ip] $KEY: pushed\n";
            }
            else {
                print $fh localtime().": [$ip] $KEY: push attempt blocked!\n";
            }
        }
    }
}
die "$KEY: You have been banned from all update operations!\n" unless $allowed;
