#!/usr/bin/perl 
#
# fix LDIF file
# - normalize telephone numbers
# - delete empty entries
# - encode all text fields base64
#
#  Michael Klemme
#  2004???? mk initial
#  20051002 mk re-worked
#


#### configure your prefixes here
$nationalcode = "+49";
$internationalprefix = "00";
$nationalprefix = "0";

use MIME::Base64;

@tellist = ("homephone", "telephonenumber", 
	    "cellphone", "facsimiletelephonenumber", "workphone");

@textlist =("dn", "cn", "sn", "givenname", "o", "locality", "streetaddress", 
	    "countryname");
@textlist =( );

%fix_fields=(
	     "homephone", "homePhone", 
	     "telephonenumber", "workPhone", 
	     "cellphone", "mobile",
	     "facsimiletelephonenumber", "fax"
	     );


while ($line = <>) {

    chomp $line;

    if ($line =~ m|^[ \t]*$|)  {
	print "\n";
	next;
    }


    ## parse line into fields
    unless ($line =~ m|(.*?)(:+)[ \t]*(.*)|)  {
	print "$line\n";
	next;
    }
    my ($key, $sep, $value) =  ($1, $2, $3);

    if ($value =~  m|^[ \t]*$|) {
	next;
    }

    ## clean up telephone numbers
    foreach $telnotype (@tellist ) {
	if ($telnotype eq lc($key)){

	    # remove Exchange garbage  "+49 (0172) "
	    $value =~ s/(.)\(0(.*)\)/$1$2/;

	    ## remove all special characters
	    # replace intenational/national prefixes by "+.." notation
	    $value =~ s|^$internationalprefix|+|;
	    $value =~ s|^$nationalprefix|$nationalcode|;

	    # delete illegal characters
	    $value =~ s|[- \t()/.]||g;
	    $value =~ s|[a-zA-Z].*||g;
	    $value =~ s|\-||g;
	}
    }

    ## encode text fields base64
    if ($sep ne "::"){ 
	foreach $texttype (@textlist ) {
	    if ($texttype eq lc($key)){
		## remove all special characters
		$value = encode_base64($value, "");
		$sep = "::";		
	    }
	}
    }

    ## fix keys
    foreach $lkey (keys %fix_fields) {
        if ($lkey eq lc($key)){
            $key=$fix_fields{$lkey};
        }
    }

    print "$key$sep $value\n"

}



exit 0;
