#!/usr/bin/perl
#
# retrieve cn of phone number ($ARGV[0]) from ldap database on localhost
# 
# 'mobile','phoneHome','telephoneNumber' fields are searched
#
# phone number can have any format (eg. +49 234/56761, 01234567, 069 12 34 56 etc. ) the best matching ist found
#
use Net::LDAP qw(:all);			# use for all code
use Net::LDAP::Util qw(ldap_error_name	
                       ldap_error_text) ; 	# use for Error handling
$ldap = Net::LDAP->new("localhost") or die "$@";# connect to ldap server on localhost or die
$mesg = $ldap->bind( version => 3 );    	# use for searches
sub LDAPsearch
{
	  my ($ldap,$searchString,$attrs,$base) = @_ ;
  	  # if they don't pass a base... set it for them
  	  if (!$base ) { $base = "dc=local"; }
	  # if they don't pass an array of attributes...
	  # set up something for them
	  if (!$attrs ) { $attrs = ['cn','mobile','phoneHome','telephoneNumber' ]; }
          my $result = $ldap->search (
                base    => "$base",
                scope   => "sub",
                filter  => "$searchString",
                attrs   =>  $attrs
                );
}

sub GetAttrib
{
# get attrib value from first entry in result
# or return "unbekannt" if no entry available
   my ($attrib,$result) =@_;	
   my @entries = $result->entries;
  if($result->count > 0)
  {	
          $res =  $entries[0]->get_value($attrib);
  }
  else
  {
	$res = "unbekannt";
  }
}
sub BuildSearchString
{
# build ldap search string for searching in @phonenames fields
  my ($phonenr) = @_;
  my @phonenames = ('telephoneNumber','homePhone','mobile');
  my $searchString = "|";
  foreach $phonename (@phonenames)
  {
    $searchString = $searchString . "($phonename=$phonenr)"; 
  }
  $result = $searchString;
}

my $phonenr = $ARGV[0]; # first and only parameter is phonenr
$phonenr =~s/^00/\+/; # substitute 00 at the beginning by a +, international number format 
my $origphonenr = $phonenr; # store original number for later use
$phonenr=~s/\D//g;# remove all non number characters from string
$phonenr=~s/(\d)/\*\1/g; # prefix all numbers with *n (eg. 12345 => *1*2*3*4*5
			 # this way 12345 will match 12 34 5 or 123/45 and so on
my @Attrs = ('cn');		# request cn
				# to be returned
my $result;
my $searchString =BuildSearchString($phonenr);
$result = LDAPsearch($ldap,$searchString,\@Attrs);
if($result->count == 0)
{
# retry with the german internatinal prefix 
  my $nr = $phonenr;
  if($origphonenr =~ /^0/) # starts with a zero
  {
    # substitute leading zero by +49
    $nr =~ s/^\*0/\+49\*/; 
    $searchString =BuildSearchString($nr);
    $result = LDAPsearch($ldap,$searchString,\@Attrs);
  }

}
if($result->count == 0)
{
# try without +49
  if($origphonenr=~/^\+49/)
  {
    $phonenr =~ s/^\*4\*9/0/; 
    $searchString =BuildSearchString($phonenr);
    $result = LDAPsearch($ldap,$searchString,\@Attrs);
  }
}

my $cn= GetAttrib("cn",$result);
print "$cn\n";
