#!/usr/bin/perl
##
## Example script to export ldap entries into an smbpasswd file format
## using the Mozilla PerLDAP module.
##
## writen by jerry@samba.org
##
## ported to Net::LDAP by dkrovich@slackworks.com

use Net::LDAP;

######################################################
## Set these values to whatever you need for your site
##

$DN="dc=samba,dc=my-domain,dc=com";
$ROOTDN="cn=Manager,dc=my-domain,dc=com";
$rootpw = "secret";
$LDAPSERVER="localhost";

##
## end local site variables
######################################################

$ldap = Net::LDAP->new($LDAPSERVER) or die "Unable to connect to LDAP server $LDAPSERVER";

print "##\n";
print "## Autogenerated smbpasswd file via ldapsearch\n";
print "## from $LDAPSERVER ($DN)\n";
print "##\n";

## scheck for the existence of the posixAccount first
$result = $ldap->search ( base => "$DN",
			  scope => "sub",
			  filter => "(objectclass=smbpasswordentry)"
			);



## loop over the entries we found
while ( $entry = $result->shift_entry() ) {

	@uid         = $entry->get_value("uid");
	@uidNumber   = $entry->get_value("uidNumber");
	@lm_pw       = $entry->get_value("lmpassword");
	@nt_pw       = $entry->get_value("ntpassword");
	@acct        = $entry->get_value("acctFlags");
	@pwdLastSet  = $entry->get_value("pwdLastSet");

	if (($#uid+1) && ($#uidNumber+1)) {

		$lm_pw[0]      = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" if (! ($#lm_pw+1));
		$nt_pw[0]      = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" if (! ($#nt_pw+1));
		$acct[0]       = "[DU         ]" if (! ($#acct+1));
		$pwdLastSet[0] = "FFFFFFFF" if (! ($#pwdLastSet+1));

		print "$uid[0]:$uidNumber[0]:$lm_pw[0]:$nt_pw[0]:$acct[0]:LCT-$pwdLastSet[0]\n";
	}

}

$ldap->unbind();
exit 0;