#!/usr/local/bin/perl

# mutt_ldap_query.pl 
# version 1.1

# Copyright (C) 4/14/98 Marc de Courville <marc@courville.org>
#       but feel free to redistribute it however you like.

# mutt_ldap_query.pl: perl script to parse the outputs of ldapsearch
# (ldap server query tool present in ldap-3.3 distribution
# http://www.umich.edu/~rsug/ldap) in order to pass the required
# formatted data to mutt (mail client http://www.cs.hmc.edu/~me/mutt/)
# using Brandon Blong's the "External Address Query" patch
# (http://www.fiction.net/blong/programs/mutt/#query).

# Please change the following 2 lines to match your site configuration

my $ldap_server = "ldap";
my $BASEDN = "o=Motorola, c=US";           

$version = "v1.1";

if ( !$ARGV[0]) 
{
  print "$0 syntax error:\n";
  print "\t Usage: $0 <name_to_query>, [[<other_name_to_query>], ...]\n";
  exit;
}       

$arguments=join ' ', @ARGV;

#print "LDAP Query: ",$arguments,"\n";

@query=split /, /, $arguments;

$count = 0;

while (@query)
{
  $askfor=shift(@query);

  open ( LDAPQUERY , "ldapsearch -h $ldap_server -b '$BASEDN' 'sn=$askfor' |") || die "LDAP query error: $!"; 

  while ( $curlin=<LDAPQUERY> )
  {
    chop($curlin);

    $ok = 0;
    SWITCH: 
    {
      if ($curlin =~ /^sn=(.*)$/s) { $lastname=$1; last SWITCH; };
      if ($curlin =~ /^fn=(.*)$/s) { $firstname=$1; last SWITCH; };
      if ($curlin =~ /^mail=(.*)$/s) { $email=$1; last SWITCH; };
      if ($curlin =~ /^telephonenumber=(.*)$/s ) { $phone=$1; $ok=1; last SWITCH; };
      $nothing=1;
    }
    if ( $ok == 1 )
    {
      $answer=$email . "\t " . $firstname . " " . $lastname . "\t phone:" . $phone;
      push(@results, $answer);
      $count++;
    }
  }

}

print "LDAP query: found $count\n";

# Do not sort the result since it will be sorted according the email address!
foreach $i (@results)
{
  print "$i\n";
}
