#!/usr/bin/perl
# $Id: ldif2trade.pl $

# $Id: ldif2trade.pl$

#   (C) 2000 Jeff Armitstead
# 
#   This software is provided 'as-is', without any express or implied
#   warranty.  In no event will the authors be held liable for any damages
#   arising from the use of this software.
# 
#   Permission is granted to anyone to use this software for any purpose,
#   including commercial applications, and to alter it and redistribute it
#   freely, subject to the following restrictions:
# 
#   1. The origin of this software must not be misrepresented; you must not
#      claim that you wrote the original software. If you use this software
#      in a product, an acknowledgment in the product documentation would be
#      appreciated but is not required.
#   2. Altered source versions must be plainly marked as such, and must not be
#      misrepresented as being the original software.
#   3. This notice may not be removed or altered from any source distribution.
# 
#   Jeff Armitstead   jeffa@gsbme.unsw.edu.au

# This program filters an ldif file and spits out tradeclient format 
# Usage:
#	ldif2 [-v] [ldif_file [output-file]]
#
# Mozilla ldif format follows
#
#dn: cn=Display_Name,mail=Email_Address
#modifytimestamp: 20010318005235Z
#cn: Display_Name
#xmozillausehtmlmail: FALSE
#givenname: First_Name
#sn: Last_Name
#mail: Email_Address
#xmozillanickname: Nickname
#o: Organisation
#locality: City
#st: State
#description:: Tm90ZXMgYW5kIHN0dWZmCmFuZCBtb3JlIHN0dWZm
#title: Title
#streetaddress:: QWRkcmVzczEKQWRkcmVzczIJ
#postalcode: Zip
#countryname: Country
#telephonenumber: WorkPhone
#homephone: HomePhone
#facsimiletelephonenumber: Fax
#xmozillauseconferenceserver: 0
#ou: Department
#pagerphone: Pager
#cellphone: Mobile
#homeurl: WebPage
#xmozillaanyphone: WorkPhone
#objectclass: top
#objectclass: person

use MIME::Base64;
require 'getopts.pl';

#=================================================================

$program = "ldif2trade";

sub usage {
    die "Usage: $program [-vh] [file [output-file]]\n";
}

#=================================================================

&Getopts("vh") || &usage;

$verbose = $opt_v;
$help = $opt_h;

if ($help)
{
    &usage;
}

$infile = shift(@ARGV);
if ($infile)
{
    open(INFILE, $infile) || die "$program: Cannot read from $infile\n";
    $handle = "INFILE";
    $ftype=`file $infile`;
}
else
{
    $handle = "STDIN";
    $ftype = "ASCII";
}


$outfile = shift(@ARGV);
if ($outfile)
{
    open(OUTFILE, ">$outfile") || die "$program: Cannot write to $outfile\n";
    select(OUTFILE);
}

$tot_conv = 0;
$tot_seen = 0;
$tot_dups = 0;

seek($handle,0,0);

if (index($ftype,"ASCII") == -1)
{
    die "$program: Error file does not appear to be LDIF format\n";


}
else
{
    $last_sur="";
    $last_given="";
    $last_mail="";
    $sep="\4";
    $blank="";

    print"BTCL0001";            # file magic number thingy

    while(<$handle>)		# massage the file
    {

	    chomp;
	    s/\s*\r$//;   # This strips the ^M's and spaces on the right.

#	if (/^cn:.*|^givenname:.*|^sn:.*|^mail:.*/)
	if (/^cn:.*/)
	  {
            $common_name = substr($_,index($_,":")+2,length($_));
	    $tot_seen++;
 	    next;
	  }
	elsif (/^givenname:.*/)
	  {
            $given_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^sn:.*/)
	  {
            $sur_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^mail:.*/)
	  {
            $mail_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^dn:.*/)
	  {
            $distinctive_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^xmozillanickname:.*/)
	  {
            $nick_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^o:.*/)
	  {
            $company_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^locality:.*/)
	  {
            $city_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^st:.*/)
	  {
            $state_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^title:.*/)
	  {
            $title_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^countryname:.*/)
	  {
            $country_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^postalcode:.*/)
	  {
            $post_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^telephonenumber:.*/)
	  {
            $workphone_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^homephone:.*/)
	  {
            $homephone_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^facsimiletelephonenumber:.*/)
	  {
            $fax_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^ou:.*/)
	  {
            $department_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^pagerphone:.*/)
	  {
            $pager_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^cellphone:.*/)
	  {
            $mobile_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^homeurl:.*/)
	  {
            $url_name = substr($_,index($_,":")+2,length($_));
 	    next;
	  }
	elsif (/^streetaddress:: .*/)
	  {
            $street_name = substr($_,index($_,"::")+3,length($_));
#	    print STDERR "[$street_name]";
#	    print STDERR "\n";
	    $street_name = decode_base64($street_name);
#	    print STDERR $street_name;
	    next;
	  }
	elsif (/^description:: .*/)
	  {
            $info_name = substr($_,index($_,"::")+3,length($_));
#	    print STDERR "[$info_name]";
#	    print STDERR "\n";
	    $info_name = decode_base64($info_name);
#	    print STDERR $info_name;
	    next;
	  }
	
	elsif ((length($_)==0)) {
	 if (($given_name eq $last_given),($sur_name eq $last_sur),($mail_name eq $last_mail))
	   {
	     $tot_dups++;
	   }
	 else
	   {
#	 print"\3\0\0\0\0$given_name\4\4$sur_name";
#         for ($k = 0; $k <= 25 ; $k++) {
#	   print("\4");
#	 }
#	 print"$mail_name\4\4$mail_name\4$mail_name\4\5\6";
	 $tot_conv++;
	 $last_sur=$sur_name;
	 $last_given=$given_name;
	 $last_mail=$mail_name;
	 $rec = [$given_name,
		 $blank,      #"blank_middle_name",        #Middle name
                 $sur_name,
		 $title_name,
		 $nick_name,
		 $blank,      #"blank_sex",        #Sex
		 $homephone_name,
		 $workphone_name,
		 $mobile_name,
		 $pager_name,
		 $fax_name,
		 $street_name,
		 $url_name,
		 $company_name,
		 $title_name,         #position
		 $street_name,
		 $city_name,
		 $state_name,
		 $post_name,
		 $country_name,
		 "blank_???",
		 $workphone_name,          #Ph 1
		 $blank,               #"blank_ph_2",          #Ph 2
		 $fax_name,
		 $pager_name,
		 $url_name,
		 $blank,               #"blank_manager",          #Manager
		 $blank,               #"blank_assistant",          #Assistant
                 $mail_name,
		 $info_name,
		 $mail_name,
		 $mail_name];

	 $table{$given_name}=$rec;

$given_name=$blank;
$sur_name=$blank;
$title_name=$blank;
$nick_name=$blank;
$homephone_name=$blank;
$workphone_name=$blank;
$mobile_name=$blank;
$pager_name=$blank;
$fax_name=$blank;
$street_name=$blank;
$url_name=$blank;
$company_name=$blank;
$street_name=$blank;
$city_name=$blank;
$state_name=$blank;
$post_name=$blank;
$country_name=$blank;
$fax_name=$blank;
$pager_name=$blank;
$url_name=$blank;
$mail_name=$blank;
$info_name=$blank;

	 next;
       }
       }
	    else {
	

	 next;
       }


	  }
  }
$verbose && print STDERR "Total records converted= $tot_conv\n";
$verbose && print STDERR "Total records seen= $tot_seen\n";
$verbose && print STDERR "Total duplicates ignored= $tot_dups\n";
%std=sort($table);
foreach $family( sort {uc($a) cmp uc($b)} (keys %table) ) {
	 print"\3\0\0\0\0";
         for ($k = 0; $k <= 31 ; $k++) {
	   print @{ $table{$family} }[$k];
	   print("\4");
	 }
	 print"\5\6";

#            print STDERR "$family: @{ $table{$family} }\n"
        }
 
exit 0;

#=================================================================


