#!/usr/bin/perl -w
# (C) 2004 Jean-Michel Dault <jmdault@mandrakesoft.com>
# This program is Free Software under the GNU General Public License (>=v2).
# Read the file COPYING that comes with this packages for details.
#
# THIS FILE MUST BE OWNED BY ROOT AND UNREADABLE BY ANYONE ELSE!
#
use URI;
use Net::LDAP;

sub mywarn{
  print "$_[0] $_[1]\n";
}

$ldap_uri="ldap://127.0.0.1:389";
$base_dn=`cat /etc/kolab/kolab.conf|grep bind_dn|cut -f2 -d:|cut -f2- -d,`;
$bind_dn="cn=manager,$base_dn";
$bind_pw=`cat /etc/kolab/kolab.conf|grep bind_pw|cut -f2 -d:|cut -f2 -d" "`;
chop $bind_pw;

$user=$ARGV[0];
print "New Password:  ";
$pass=<STDIN>;
chomp $pass;

$pass=`/usr/sbin/slappasswd -s $pass`;

my $ldapuri = URI->new($ldap_uri) || mywarn "error: could not parse given uri";
my $ldap = Net::LDAP->new($ldapuri->host, port=> $ldapuri->port) || mywarn "could not connect ldap server";
if ($ldap) {
   $ldap->bind($bind_dn, password=> $bind_pw) || mywarn "could not bind to ldap";
   my $mesg = $ldap->search(base=> "$base_dn", scope=> 'sub', filter=> "(&(uid=$user)(objectClass=*))");
   @entries = $mesg->entries;
   $dn=$entries[0]->dn();
}

if(!$dn) {
   print "Cannot find user $user!.\n";
} else {
   $mesg=$ldap->modify($dn, replace=> { 'userPassword' => $pass } );
   if($mesg && $mesg->code) {
      mywarn "Failed to update password: ", $mesg->error;
   } else {
      print "Done modifying user $user\n";
   }
}

exit 0;