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

#Description: Finds if a user is active
#creates a file called $filename with a line format:
#$uidnumber:$uid:$status:$cn
#Tested and cleaned up: 08/11/2002

#big bad global variables
my $start_uid;
my $end_uid;

#STDIN to the start uid
while ( $start_uid eq undef ) {
    print("Enter in start uidnumber\n");
    chomp( $start_uid = <STDIN> );

    if ( ( $start_uid < 1000 ) || ( $start_uid > 10000 ) ) {
        undef($start_uid);
    }
}

#STDIN to the end uid
while ( $end_uid eq undef ) {
    print("Enter in end uidnumber\n");
    chomp( $end_uid = <STDIN> );

    if ( ( $end_uid < $start_uid ) || ( $end_uid > 10000 ) ) {
        undef($end_uid);
    }
}

#other global variables
my $begin    = $start_uid;
my $end      = $end_uid;
my $filename = "active.list";

#echo what you requested
print "The Start is $begin and the End $end\n";

#check to see if the filename exists 
if ( -f $filename ) { die "$filename exists :$!\n"; }

#if filename does not exist it is created 
print "creating filename $filename\n";

#simple loop that follows the limits set previously
my $i; #counter
for ( $i = $begin ; $i < $end ; $i++ ) {
    my $status1 = check_ldap_uid($i);
    open( LOG, ">>$filename" );
    if ( $status1 eq undef ) { $status1 = "$i:empty_uid"; }
    print LOG "$status1\n";
    close(LOG);
}

sub check_ldap_uid {

    #subfunction to check for uid in ldap
    my ($uidnumber) = shift;
    my ( $searchFilter, $myldapserver, $searchResultsObject, $ldap, $mailbase,
        $attributesToReturn, $index, $entry, $status, $cn, $uid );

    # The attributes (and their associated values) that we wish to
    #  search for in the directory.
    $searchFilter = "(uidnumber=$uidnumber)";

    $myldapserver = "localhost";
    $mailbase     = "ou=mailaccounts,dc=somecollege,dc=edu";

    $attributesToReturn = [ 'uid', 'cn', 'accountstatus' ];

    #Open a connection to the directory
    #
    $ldap = Net::LDAP->new($myldapserver)    # as struct
      or die "$@";

    $searchResultsObject = $ldap->search(
        base   => $mailbase,            # Note the comma here
        filter => $searchFilter,        # and here
        attrs  => $attributesToReturn
    );

    if ( $searchResultsObject->code ) {
        print "An error occurred during the LDAP search attempt:\n";
        die $searchResultsObject->error;
    }

    #$ldap->unbind;

    my $countOfEntriesReturned = $searchResultsObject->count;
    for ( my $index = 0 ; $index < $countOfEntriesReturned ; $index++ ) {
        my $entry = $searchResultsObject->entry($index);
        $uid    = $entry->get_value('uid');
        $cn     = $entry->get_value('cn');
        $status = $entry->get_value('accountstatus');
    }

    if ( $status eq undef ) {
        return undef;
    }
    else { return "$uidnumber:$uid:$status:$cn"; }
}
