#!/usr/bin/perl
use Net::LDAP;
use Net::LDAP::LDIF;
use Unix::PasswdFile;
use strict;
use warnings;

# This should end up so that it either slapcats or uses an existing file
my $ldifLocation = "20080912.ldif";
my $passwdfile = "20080912a.passwd";
my $now = localtime(time);

# Open our LDIF file
my $ldifFile = Net::LDAP::LDIF->new($ldifLocation,"r",onerror => 'undef' );

# Open unix passwd file
my $pwdFile = new Unix::PasswdFile("$passwdfile",,mode => "r+") or die "new Unix::PasswdFile didn't work for some reason: $@\n";


#loop through the ldif
while ( not $ldifFile->eof () ) {
        my $currentEntry = $ldifFile->read_entry();
        if ( $ldifFile->error ( ) ) {
                print "Error msg: ", $ldifFile->error(), "\n";
                print "Error lines:\n", $ldifFile->error_lines(), "\n";
        } else {

                my $userPassword = $currentEntry->get_value('userPassword',asref => 1);
                if (defined ($userPassword)) {
                        my $userUID = $currentEntry->get_value('UID',asref=>1);
                        my $userCN = $currentEntry->get_value('cn',asref=>1);
                        my $userDisplayName = $currentEntry->get_value('displayName',asref=>1);
                        my @gecos;
                        if (defined ($userDisplayName)) {

                                @gecos=@$userDisplayName;
                }       else {
                                @gecos=@$userCN;
                }

                        # Iterate elements of gecos, removing any dash-separated items
                        my $gecosSize = @gecos;
                        for (my $i=0;$i<$gecosSize;$i++) {
                                print "loop $i\n";
                                $gecos[$i] =~ s/(.*)-(.*)/$1\ $2/gi;
                        }



                        # Convert MD5 passwords to something John can handle
                        # Currently broken, and,
                        # still need something in here to handle CRYPT
                        #my ($outputPW) = @$userPassword;
                        #print "oldpw: $outputPW          ";
                        #$outputPW =~ s/\{MD5\}(\C{22}).*/\$1\$\$\1/gi;
                        #$outputPW =~ s/\{SMD5\}(\C{5})(\C{22}).*/\$1\$\1\$\2/gi;
                        $pwdFile->user(@$userUID,$outputPW,"","",@gecos,"","");
                }
        }
}
