#! /usr/bin/perl

use warnings;
use strict;

use Net::LDAP;

use constant PASSWORD_FILE => '/tmp/password.txt';
use constant ICT_LDAP_SERVER => 'ldap.tyict.vtc.edu.hk';
use constant ICT_DIR_BASE => 'ou=People,dc=tyict,dc=vtc,dc=edu,dc=hk';
sub read_password() {
    open PW, "<", PASSWORD_FILE
        or die "unable to open ", PASSWORD_FILE, ": $!";
    my $pass = <PW>;
    close PW;
    chomp $pass;
    return $pass;
}

our $uid    = "nicku";
our $base   = ICT_DIR_BASE;
our $server = ICT_LDAP_SERVER;
our $new_descr = shift
    or die "Need a descption as a single command line parameter\n";

our $ldap = Net::LDAP->new( $server ) or die "$@";
$ldap->start_tls( verify => 'none' ) or warn "Unable to start_tls\n";
my $r = $ldap->bind;

# First we get the DN of the entry we will bind with.  At the same
# time, we'll get the old value of the description attribute:
my $mesg = $ldap->search(
                         base   => $base,
                         filter => "(uid=$uid)",
                         attrs  => [ 'description' ],
                        );

$mesg->code && die $mesg->error;
$mesg->count == 1 or die "Got ", $mesg->count, " entries instead of 1.\n";
our $entry = $mesg->pop_entry;
print $entry->dump; # Show the old description.
our $dn = $entry->dn;

# Then we bind with that DN, change the description, and show the
# resulting entry:
$r = $ldap->bind( $dn, password => read_password );

$mesg = $ldap->modify( $dn, replace =>  { description => $new_descr } );
$mesg = $ldap->search(
                      base   => $dn,
                      scope  => 'base',
                      filter => "(uid=$uid)",
                      attrs  => [ '*' ],
                     );

$mesg->code && die $mesg->error;
$mesg->count == 1 or die "Got ", $mesg->count, " entries instead of 1.\n";
print +( $mesg->pop_entry )->dump;
$ldap->unbind;
