#!/usr/intel/bin/perl

# mutt_four11_query.pl 
# version 1.0

# based on mutt_ldap_query.pl 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).
#
# This version was modified to use the public LDAP server offered by 
# Four11.com

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

my $ldap_server = "ldap.four11.com";
my $BASEDN = "c=US";           

$version = "v1.0";

if ($ARGV[0] eq "-m")
{
  $mutt = 1;
  shift (@ARGV);
}

if ( !$ARGV[0]) 
{
  print "$0 syntax error:\n";
  print " Usage: $0 [-m] <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' 'cn=$askfor' |") || die "LDAP query error: $!"; 

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

    $ok = 0;
    SWITCH: 
    {
      if ($curlin =~ /^sn=(.*)$/) { $lastname=$1; last SWITCH; };
      if ($curlin =~ /^fn=(.*)$/) { $firstname=$1; last SWITCH; };
      if ($curlin =~ /^cn=(.*)$/) { $name=$1; last SWITCH; };
      if ($curlin =~ /^mail=(.*)$/) { $email=$1; last SWITCH; };
      if ($curlin =~ /^telephonenumber[=:](.*)$/s ) { $phone=$1; last SWITCH; };
      if ($curlin =~ /^o=(.*)$/ ) { $labeledURI=$1; last SWITCH; };
      if ($curlin =~ /^l=(.*)$/ ) { $location=$1; last SWITCH; };
      if ($curlin =~ /^st=(.*)$/ ) { $state=$1; last SWITCH; };
      if ($curlin =~ /^c=(.*)$/ ) { $country=$1; last SWITCH; };
      if ($curlin =~ /^$/) {$ok = 1; last SWITCH; };
      $nothing=1;
    }
    if ( $ok == 1 )
    {
      if ($mutt)
      {
	$answer=$email. "\t$name". "\t ";
	$answer .= $location if (defined($location));
	$answer .= ", " . $state if (defined($state));
	$answer .= " " . $country if (defined($country));
	$answer .= " " . $phone if (defined($phone));
	$answer .= "\t [four11]";
      }
      else
      {
	$answer = sprintf ("%-40.40s  %s %s %s %10s", 
			   $name ." <".$email."> ", $location, $state, 
			   $country, $phone);
      }
      $country = ""; $location = ""; $labeledURI = ""; $state = "";
      $phone = "";
      undef($country, $location, $labeledURI, $state, $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";
}
