#!/usr/bin/perl
use Net::LDAP qw(:all);

open(INF,"ldap_server_info.dat") or die("Couldn't open ldap_server_info for reading: $! \n");
@data = <INF>;
close(INF);

foreach $i (@data) {
   
       ($host,$port,$binddn,$bindpass,$basedn,$withroot) = split(/\|/,$i);
       print "\nThe parameters are host :$host , port:$port, binddn: $binddn , bindpass: $bindpass,basedn: $basedn\n ";
                
           $ldap = Net::LDAP->new($host,
				   port=>$port) or die "$@";

           $mesg =$ldap->bind($binddn,
				  password=>$bindpass);

				  if( $mesg->code == 0) 
	                   {
                           $result = ldap_delete_tree($ldap ,$withroot,$basedn);
                              if( $result == 0){
					                  print " The ldap server $host could not be cleaned\n" ;}
				               else{
					                  print " The ldap server $host has been be cleaned\n" ;}

					   }
					else{	
                           print "\n The connection to ldap server $host could not be executed\n " ;}


  }






sub ldap_delete_tree {
    my $ldap = shift;
	my $withroot=shift;
    my @dn = @_;
    my $msg = $ldap->search( base => $dn[0],
				 scope => 1,
				 filter => "(objectclass=*)",
				 attr => [ "1.1" ]
				 );
    unless( $msg->code() == 0 ) {
	  
	    return 0;
    }
    print "\n1  @dn\n";
    if ($msg->count) {
	   
	    unshift @dn, $msg->entries;
	 
    }
    
	if( $withroot == 0)
	{
		pop @dn;
    }
    while (@dn) {
       $msg = $ldap->search( base => $dn[0],
				 scope => 1,
				 filter => "(objectclass=*)",
				 attr => [ "1.1" ]
				 );
	unless( $msg->code() == 0 ) {
	  
	    return 0;
	}
	if ($msg->count) {
	    #
	    # We have children
	    #
	    unshift @dn, $msg->entries;
            next;
	}
	# And then ourselves
	$msg = $ldap->delete( shift @dn );
	unless( $msg->code() == 0 ) {

	    return 0;
	}
    }

    return 1;
}





























