#!/usr/bin/perl
#
# userv-git-daemon service script
#
# This was written by Tony Finch <dot@dotat.at>
# You may do anything with it, at your own risk.
# http://creativecommons.org/publicdomain/zero/1.0/

use strict;
use warnings;

use Sys::Syslog;

our $check_repo = 1;
our $check_export = 0;
our ($service,$client,$dir,$repo);

${$main::{$_}} = $ENV{"USERV_U_$_"}
    for grep s/^USERV_U_//, keys %ENV;

openlog 'userv-$service', 'pid', 'daemon';
sub fail { syslog 'err', "$client @_"; exit }

$_ = our $uri;
for my $cf (@ARGV) { do $cf }

fail "no repository configured for $uri" unless defined $repo;
fail "no directory configured for $uri"  unless defined $dir;

my $home = (getpwuid $<)[7];
$dir = "$home/$dir" if $dir =~ m|^[^/]|
                    or $dir =~ s|^~/||;
$dir = "$dir/$repo";

fail "bad repository in $uri"
    if $check_repo and $repo !~ /^[0-9A-Za-z._-]+[.]git$/;
fail "repository not exported for $uri"
    if $check_export and not -e "$dir/git-daemon-export-ok";

my @cmd = ($service, '--strict', '--timeout=30', $dir);
no warnings; # suppress errors to stderr
exec @cmd or fail "exec @cmd: $!";

# end
