#!/usr/bin/perl
use strict;
use warnings;

use lib $ENV{GL_LIBDIR};
use Gitolite::Rc;
use Gitolite::Common;
use Gitolite::Conf::Load;

=for usage
Usage:  gitolite access [-q] <repo> <user> <perm> <ref>

Print access rights for arguments given.  The string printed has the word
DENIED in it if access was denied.  With '-q', returns only an exit code
(shell truth, not perl truth -- 0 is success).

  - repo: mandatory
  - user: mandatory
  - perm: defauts to '+'.  Valid values: R, W, +, C, D, M
  - ref:  defauts to 'any'.  See notes below

Notes:
  - ref: Any fully qualified ref ('refs/heads/master', not 'master') is fine.
    The 'any' ref is special -- it ignores deny rules (see docs for what this
    means and exceptions).

Batch mode: see src/triggers/post-compile/update-git-daemon-access-list for a
good example that shows how to test several repos in one invocation.  This is
orders of magnitude faster than running the command multiple times; you'll
notice if you have more than a hundred or so repos.
=cut

usage() if not @ARGV or $ARGV[0] eq '-h';
my $quiet = 0;
if ( $ARGV[0] eq '-q' ) { $quiet = 1; shift @ARGV; }

my ( $repo, $user, $aa, $ref ) = @ARGV;
$aa  ||= '+';
$ref ||= 'any';
_die "invalid perm" if not( $aa and $aa =~ /^(R|W|\+|C|D|M|\^C)$/ );
_die "invalid ref name" if not( $ref and $ref =~ $REPONAME_PATT );

my $ret = '';

if ( $repo ne '%' and $user ne '%' ) {
    # single repo, single user; no STDIN
    $ret = access( $repo, $user, $aa, $ref );

    if ( $ret =~ /DENIED/ ) {
        print "$ret\n" unless $quiet;
        exit 1;
    }

    print "$ret\n" unless $quiet;
    exit 0;
}

$repo = '' if $repo eq '%';
$user = '' if $user eq '%';

_die "'-q' doesn't go with using a pipe" if $quiet;
@ARGV = ();
while (<>) {
    my @in = split;
    my $r  = $repo || shift @in;
    my $u  = $user || shift @in;
    $ret = access( $r, $u, $aa, $ref );
    print "$r\t$u\t$ret\n";
}
