#!/usr/bin/env perl

use strict;
use warnings;

my $who = ($ENV{REMOTE_USER} || die "Auth required\n")."\@$ENV{REMOTE_ADDR}";
my $base = $ENV{GIT_DIR} or die "GIT hook ENV malfunction!\n";
my $lock_dir = "$base/logs";
mkdir $lock_dir, 0755 unless -d $lock_dir;

my $last_pushed = "$lock_dir/pushed";
open my $fh, ">", $last_pushed or die "$last_pushed: open: $!";
print $fh localtime().": [$ENV{REMOTE_ADDR} $ENV{REMOTE_PORT} => $ENV{SERVER_ADDR} $ENV{SERVER_PORT}] Pushed by: $ENV{REMOTE_USER}\n";
close $fh;

# $lock_file = "$lock_dir/$REMOTE_ADDR-$REMOTE_USER.lock"; # Created by push-notification
foreach my $lock_file (glob "$lock_dir/*.lock") {
    if (open my $fh, "<", $lock_file) {
        if (defined (my $worker = <$fh>) and
            defined (my $sleeper = <$fh>)) {
            chomp $worker;
            chomp $sleeper;
            if (kill 0, $worker and
                kill 9, $sleeper) {
                if ($lock_file =~ m{.*/(.+).lock$}) {
                    warn localtime().": [$who] git-server: Sending push notification to $1 ...\n";
                }
                else {
                    die localtime().": [$who] git-server: Released impossible sleeper (pid=$sleeper) ...\n";
                }
            }
        }
        close $fh;
    }
}
