#!/usr/bin/perl
# Volker Stolz <stolz@i2.informatik.rwth-aachen.de>, 2005
# v1.0 -- initial version
# v1.0.1 -- skip entries w/o email-address
# No strings attached

use Net::LDAP;
# http://search.cpan.org/~gbarr/perl-ldap-0.3202/lib/Net/LDAP.pod
use Unicode::MapUTF8 qw(from_utf8);
# http://www.nihongo.org/snowhare/utilities/modules/unicode-maputf8/

# Fields to search in the LDAP database
#######################################
my @fields = qw(cn mail);

my $search_limit = 50;
my $charset = 'ISO-8859-15';

die "Usage: $0 <name_to_query>, [[<other_name_to_query>], ...]\n"
    if ! @ARGV;


$/ = '';	# Paragraph mode for input.
my @results;
my $askfor;
my $skipped = 0;

foreach my $tmp ( @ARGV ) {
 $askfor = $askfor." ".$tmp if($askfor);
 $askfor = $tmp unless($askfor);
}

my $query = join '', map { "($_=*$askfor*)" } @fields;

$ldap = Net::LDAP->new( 'abook.rwth-aachen.de' ) or die "$@";

$mesg = $ldap->bind ;    # an anonymous bind

$mesg = $ldap->search( # perform a search
		      base   => "o=abook",
		      filter => "(|$query)",
		      attrs  => ['sn', 'givenName', 'mail', 'telephoneNumber', 'title', 'personaltitle', 'ou', 'o'],
		      sizelimit => $search_limit
		     );
 
 $mesg->code && die $mesg->error;
 
 foreach $entry ($mesg->entries) {
   my $email = $entry->get_value('mail');
   if ($email eq "") { $skipped++; next };
   my @name = ($entry->get_value('givenName'), $entry->get_value('sn'));
   my $phone = $entry->get_value('telephoneNumber');
   my $title = $entry->get_value('title');
   my $perstitle = $entry->get_value('personaltitle');
   my $ou = $entry->get_value('ou');
   push @results, from_utf8({-string => "$email\t@name\t[$phone]  ($title, $perstitle, $ou)\n", -charset => $charset});
   #push @results, "$email\t@name\t[$phone]  ($title, $perstitle, $ou)\n";
}
 
 $mesg = $ldap->unbind;   # take down session

# output
print "LDAP query: found ", scalar(@results)+$skipped, " (",$skipped," skipped) [Quelle: Mail- und Telefonverzeichnis der RWTH Aachen (abook.rwth-aachen.de)]\n", @results;
exit 1 if ! @results;
