#! /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    = shift || "nicku";
our $base   = shift || ICT_DIR_BASE;
our $server = shift || ICT_LDAP_SERVER;
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:
# See under Net::LDAP under search, attrs.
my $mesg = $ldap->search(
                         base   => $base,
                         filter => "(uid=$uid)",
                         attrs  => [ '1.1' ], # Just get DN
                        );

$mesg->code && die $mesg->error;
$mesg->count == 1 or die "Got ", $mesg->count, " entries instead of 1.\n";
our $dn = ( $mesg->pop_entry )->dn;

# Then we bind with that DN, and get the userPassword attribute from
# the entry:
$r = $ldap->bind( $dn, password => read_password );
$mesg = $ldap->search(
                      base   => $dn,
                      scope  => 'base',
                      filter => "(uid=$uid)",
                      attrs  => [ 'userPassword' ],
                     );

$mesg->code && die $mesg->error;
$mesg->count == 1 or die "Got ", $mesg->count, " entries instead of 1.\n";

# Then print the entry:
print +( $mesg->pop_entry )->dump;
$ldap->unbind;
