#!/usr/bin/perl
#
# This is very simple method to get data from LDAP and
# converts it to abook readable format.
# Script get only first email of any person. This is, probably,
# primary address.
# If you have better/simpler method - send me, please.
#
# You MUST have ldap-utils installed on your system to
# use this script. Without ldapsearch script does not work!
#
# Author: Mariusz Balewski <M.Balewski@wp.pl>
# 03.06.2004
#
# GPL licensed
# Feel free to send me your comments
#
# I'm not programmer, so REMEMBER:
# YOU USE THIS SCRIPT ON YOUR OWN RISK!!!
#

# Change this section to your local settings
  # Your LDAP host
  $HOST="ldaphost.com";

  # Base dn to search
  $BASEDN="\"-b ou=example,dc=com\"";

  # dn which contains email addresses
  $FINDDN="mail";

  # for example "-D \"cn=admin,dc=com\"" (if needed)
  $AUTHDN="";

  # ldap password (if needed), or -w to force script
  # to password prompting
  $PASS="";

  # use -x if your ldaphost accept simple authentication
  # or leave empty
  $SIMPLEAUTH="";

  # Where you want to put results?
  # In this example results will be putted to
  # your home directory, to abookFromLDAP file.
  # If you wish to use abook with this file, simply run:
  # abook --datafile $HOME/abookFromLDAP
  $DESTFILE="$ENV{'HOME'}/abookFromLDAP";

  # If you wish to see communiats in english or polish
  # link comms.pl-en to comms.pl to english or
  # comms.pl-pl to polish

# End of configuration
###############################
###############################

require 'comms.pl';

system("ldapsearch -h $HOST $SIMPLEAUTH $AUTHDN $PASS \"$FINDDN=*\" $BASEDN -LLL > /tmp/ldap2abook.tmp");

$i=0;
open(F1,"</tmp/ldap2abook.tmp") || die "$TMPERR";
open(F2,">$DESTFILE") || die "$DESTFILEERR";
 flock(F1,8);
 flock(F2,8);
  while(<F1>){
     if ($_ =~ m/^gecos/g){
         s/^ //g;
         s/^gecos: /name=/g;
         print F2 "[$i]\n";
         print F2 $_;
         $i++;
     }
     elsif ($_ =~ m/^mail/g){
         s/^mail: /email=/g;
         print F2 "$_\n";
     }
  }
  flock(F2,2);
  flock(F1,2);
close(F2);
close(F1);

system("rm /tmp/ldap2abook.tmp");

print "\n$i ";
print "$REPORT\n\n";

#== END
