#!@l_prefix@/bin/perl
##
##  ypanything.group.pl: LDAP group provider
##

use IO::File;
use MIME::Base64;

#   configuration
my $host         = "localhost";
my $port         = "389";
my $bindDN       = "CN=Directory Manager";
my $bindPassword = "secret";
my $base         = "O=example.com";
my $searchType   = "sub";
my $ldapsearch   = "@l_prefix@/bin/ldapsearch";
    
#   query directory via LDAP
my $ldap = new IO::File
    "$ldapsearch -x -LLL -h '$host' -p '$port'" .
    " -D '$bindDN' -w '$bindPassword' -b '$base' -s '$searchType'" .
    " objectClass=posixGroup" .
    " cn userpassword gidnumber memberuid |"
    or die "$!";
my @gr = ();
my $gr; $gr = undef;
while (<$ldap>) {
    if (m/^\s*$/) {
        if (defined($gr)) {
            push(@gr, $gr);
            $gr = undef;
        }
    }
    elsif (m/^([^:]+)::\s*(.*?)\s*$/) {
        $gr->{$1} .= (defined($gr->{$1}) ? $gr->{$1} . "," : "") . MIME::Base64::decode($2);
    }
    elsif (m/^([^:]+):\s*(.*?)\s*$/) {
        $gr->{$1} = (defined($gr->{$1}) ? $gr->{$1} . "," : "") . $2;
    }
}
$ldap->close();

#   post-processing and output generation
my $O = "";
foreach my $gr (@gr) {
    $gr->{"userpassword"} ||= "*";
    $gr->{"userpassword"} =~ s/\{crypt\}//ig;
    $O .= sprintf("%s:%s:%s:%s\n",
        $pw->{cn}, $pw->{userpassword}, $pw->{gidnumber}, $pw->{memberuid}
    );
}

#   provide output
print STDOUT $O;
exit(0);

