#!/usr/bin/perl
#
# AUTHPROTOCOL: STDIN
#
use strict;
use Getopt::Std;
use lib qw(/usr/share/benno-auth-modules);
use Benno::LDAP::Config;
use Benno::LDAP;


our(%opts);
getopts('hvc:', \%opts);
$opts{'h'} && help_exit();

print STDERR "Give <username>\\n<password>:\n" if ! -p STDIN;

my $firstline  = <STDIN>;
my $secondline = <STDIN>;
chomp $firstline;
chomp $secondline;

my ($uid,$pass);
if (!$secondline) {
    # AUTHPROTO: STDIN
    ($uid,$pass) = split /\s+/,$firstline,2;
}
else {
    # AUTHPROTO: STDIN2
    $uid = $firstline;
    $pass = $secondline;
}

my $configfile  = $ENV{CONFIG}  || $opts{'c'} || '/etc/benno-web/ldapauth.conf';
my $verbose     = $ENV{VERBOSE} || $opts{'v'};
my $DEBUG       = $ENV{DEBUG};  # LDAP DEBUG LEVEL

if (!$pass) {
    print "ERROR ERR_NOPASS\n";
    print STDERR "Aufruf: $0 <username> <passwort>\n";
    exit 1;
}

print STDERR "Read config: $configfile\n" if $verbose;
my $Conf = new Benno::LDAP::Config($configfile);
$Conf->set('DEBUG',$DEBUG);
if (!$Conf->get('host')) { # early exit
    print "NOTE LDAP host not configured. Exit.\n";
    exit 0;
}

## keep original UID (needed for DN)
my $orig_uid = $uid;

if ($Conf->get('remove_domainsuffix')) {
    $uid =~ s/\@.+$//;
}

my $LDAP;
if ($Conf->get('usersuffix') and not $Conf->get('userfilter')) {
    # search not necessary, thus overwrite settings with current user data
    $Conf->set('binddn',$Conf->get('userattr').'='.$uid.','.$Conf->get('usersuffix'));
    $Conf->set('password',$pass);
}
if (!$Conf->get('binddn')) {
    print STDERR "Try anonymous bind to LDAP server.\n" if $verbose;
}
else {
    print STDERR 'Connect to '.$Conf->get('host').' with: '.$Conf->get('binddn')."\n" if $verbose;
}
$LDAP = Benno::LDAP->new($Conf);

# convert $orig_uid to DN if groupattr_has_dn is true
if ($Conf->get('groupattr_has_dn')) {
	my $dn = $LDAP->get_user_dn($orig_uid,$Conf);
	if ($dn) {
		$uid = $dn;
	} else {
		print STDERR "Could not get DN of \"$orig_uid\"\n";
	}
}

my @addresses;
my @retlist;
foreach my $groupobj ($LDAP->get_groups($uid,$Conf)) {
    push @retlist, $groupobj->get_value($Conf->get('groupmailattr'));
    next unless @retlist;
    push @addresses, @retlist;
}

@addresses = Benno::LDAP::Config->format_addresslist(@addresses);

foreach my $address (@addresses) {
    print "MAIL $address\n";
}


### SUBS #######################################################################
sub help_exit
{
    print "Usage: $0 [-h] [-v] [-c <configfile>]\n";
    print "\n";
    print "  -c <configfile>    Configfile (default /etc/benno-web/ldapauth.conf)\n";
    print "  -v                 Verbose output\n";
    print "  -h                 This help\n";

    exit;
}


### EOP ###
1;
