# bugfix for bad birthday format
#
#
#
use strict;
use Net::LDAP;

#-----------------------------------------------------------------------
sub parse_file {
    my $file = shift;
    my @searchfor = @_;

    my @erg = ();
    my $found = 0;

    my @a = read_file($file);

    for(my $i=0; $i<=$#searchfor; $i++) {
        foreach (@a) {
            if($_ =~ /^$searchfor[$i]/i) {
                $_ =~ s/$searchfor[$i]\s*(.*)/$1/i;
                chomp($_);
                push @erg, $_;
                $found = 1;
                last;
            }
        }
        if($found != 1) {
            push @erg, "";
        } else {
            $found = 0;
        }
    }
    return @erg;
}
#-----------------------------------------------------------------------

#-----------------------------------------------------------------------
sub read_file($) {
  my $file = shift;
  local *F;
  open F, $file || die "Couldn't open file '$file' for reading: $!; aborting";
  local $/ unless wantarray;
  <F>;
}
#-----------------------------------------------------------------------


my $ADMINpasswd = shift;
my ($basedn, $ldapserver, $ldapport) = parse_file("/etc/openldap/ldap.conf", "BASE", "HOST", "PORT");

#connecting the server
my $ldap = Net::LDAP->new($ldapserver, port=>$ldapport, version => 3);
if(!defined $ldap) {
	die "can't contact LDAP Server: $ldapserver";
}
my $mesg = $ldap->bind(
                        dn => 'uid=cyrus,'.$basedn,
                        password => $ADMINpasswd
              );
if($mesg->code != 0) {
	die "bind failed";
}
$mesg = $ldap->search ( 
			base   => $basedn,
			scope  => 'one',
			attrs  => ['birthday','uid'],
			filter => '(&(uid=*)(birthday=*))'
			);

foreach my $entry ($mesg->all_entries) {
	my $uid      = $entry->get_value('uid');
	my $birthday = $entry->get_value('birthday');
	my $dn       = $entry->dn();

        my $newbirthday = $birthday;
	$newbirthday =~ tr/./-/;
	if( $newbirthday =~ /(\d{2})-(\d{2})-(\d{4})/ ) {
		$newbirthday = "$3-$2-$1";
	}
        $newbirthday =~ /(\d{4})-(\d+)-(\d+)/;
        $newbirthday = sprintf("$1-%02d-%02d",$2,$3);
	print "analysing $uid: birthday befor: $birthday birthday after: $newbirthday\n";
	if($newbirthday ne $birthday) {
		print "modify birthday for $uid\n";
		$ldap->modify(	dn	=> $dn,
				replace => { 'birthday' => $newbirthday }
			);
	}
	
}
