#!/usr/bin/perl
use strict;
use Net::LDAP;

# Code Copyright (2007) Ray Burkholder & One Unified
# May not be used without attribution
# ray@oneunified.net

# Connect and bind
my $ad = Net::LDAP->new("globalcatalog.example.com")
         or die "Could not connect!";
my $mesg = $ad->bind('username@example.com', password=>"password", version => 3 );
print( 'Bind Name: ' . $mesg->error_name() . "\n" );
print( 'Bind Message: ' . $mesg->error_text() . "" );
print( 'Bind Error: ' . $mesg->error() . "\n" );
print( 'Bind DN: ' . $mesg->dn() . "\n" );
print( 'Bind isError: ' . $mesg->is_error() . "\n" );
#Dump( $mesg );
my ( $base, $filter, $attrs );
my ( $mesg, $count );
my $targetmembership = 'TacacsReadWrite';
$base = 'DC=example,DC=com';
$filter = "&(samaccountname=$targetmembership)(objectClass=group)";
$attrs = ['distinguishedName'];
$mesg = $ad->search( base => $base, filter => $filter, attrs => $attrs );
$count = $mesg -> count;
print( "first count = $count\n" );
if ( 1 == $count ) {
 my $max = $mesg->count;
 for ( my $i = 0 ; $i < $max ; $i++ ) {
   my $entry = $mesg->entry ( $i );
   foreach my $attr ( $entry->attributes ) {
     print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n";
   }
 }
print( "=========\n" );
# check for presense of attribute first then:
#http://search.cpan.org/~gbarr/perl-ldap-0.34/lib/Net/LDAP/Search.pod
my $dn =  $mesg->entry( 0 ) -> get_value( 'distinguishedName' );
print( "dn is $dn \n" );
$filter = "&(samaccountname=tacacsuser)(objectClass=person)(memberOf=$dn)";
$mesg = $ad->search( base => $base, filter => $filter, attrs => $attrs );
$count = $mesg -> count;
print( "second count = $count\n" );
 my $max = $mesg->count;
 for ( my $i = 0 ; $i < $max ; $i++ ) {
   my $entry = $mesg->entry ( $i );
   foreach my $attr ( $entry->attributes ) {
     print join( "\n ", $attr, $entry->get_value( $attr ) ), "\n";
   }
 }

} # first count == 1

