use constant MAXUID => 65000;
use constant MIN_UID => 2000;

# Search one level down from $base for $attribute
# with biggest value less than MAXUID
# Return this value plus 1 if found
# Return 0 if none found.
sub search_for_next_available($$$$) {
    my ( $ldap, $base, $filter, $attribute ) = @_;
    my $search = $ldap->search( 
                               base => $base,
                               scope => 'one',
                               filter => $filter,
                               attrs => [ $attribute ],
                              );
    die_on_error $search;
    my $max = -1;
    foreach my $e ( $search->entries ) {
        $max = $e->get_value( $attribute )
            if $e->get_value( $attribute ) > $max and
               $e->get_value( $attribute ) < MAXUID;
    }
    return $max + 1;
}

# Search for the next available uidNumber (!!!)
# $suffix will be the value 'ou=your_student_ID,o=ICT' in this assignment.
# Assumes you have already bound with permission to read the uidNumbers
sub search_for_next_available_uidNumber($$) {
    my ( $ldap, $suffix ) = @_;
    my $uid = search_for_next_available $ldap, "ou=People,$suffix",
        '(objectClass=posixAccount)', 'uidNumber';
    return $uid if $uid > MIN_UID;
    return MIN_UID;
}
