#!/usr/bin/perl -w -I/opt/eprints2/perl_lib

use Net::LDAP;
use Net::LDAP::Constant;
use strict;

# Get username
my ($user_sent) = $ARGV[0];

# Start connection
my $ldap = Net::LDAP->new( "ldap.host.name", version => 3 );
unless( $ldap )
{
	print STDERR "LDAP error: $@\n";
	exit 1;
}

# LDAP Version
print STDERR "Using LDAP protocol version " . $ldap->version . "\n";

# Check for SSL support
my $dse = $ldap->root_dse();
if( $dse->supported_extension( &Net::LDAP::Constant::LDAP_EXTENSION_START_TLS ) )
{
	print STDERR "LDAP_EXTENSION_START_TLS supported\n";
	# Use encrypted connection if the server supports it
	my $ssl = $ldap->start_tls( sslversion => "sslv2" );
	if( $ssl->code() )
	{
		print STDERR "SSL error: " . $ssl->error() . "\n";
	}
}

# Bind 
# If anonymous binding doesnt work, call bind() with a distinguished name
# and password
my $mesg = $ldap->bind;
#my $dn = "";
#my $pword = "";
#my $mesg = $ldap->bind( $dn, password=>$pword ); 
if( $mesg->code() )
{
	print STDERR "Bind error: " . $mesg->error() . "\n";
	exit 1;
}

# Search for user
my $base = "ou=user,dc=domain,dc=name";
my $result = $ldap->search (
	base	=> "$base",
	scope   => "sub",
	# search the field that the server uses to store usernames
	# this may be 'samaccountname', or 'cn', or something else!
	filter  => "samaccountname=$user_sent", 
	sizelimit=>1
);
if( $result->code() )
{
	print STDERR "Search error: " . $result->code() . " " . $result->error() . "\n";
	exit;
}

my $entr = $result->pop_entry;
unless( defined $entr )
{
	print STDERR "No search results returned\n";
	exit 1;
}
print $entr->dump;
print $entr->get_value( "distinguishedName" ), "\n";

$ldap->unbind;
