#!/usr/bin/perl

use Net::LDAP;
use Net::LDAP::LDIF;
use Net::LDAP::Control;
use Net::LDAP::Util qw(ldap_error_name);
use Net::LDAP::Util qw(ldap_error_text);
use Net::LDAP::Message;
use Net::LDAP::Search;

$fqdn = "localhost.localdomain";
$port = 389;
$binddn = "cn=directory manager";
$binddnpw = "Secret12";
$groupdn = "cn=large-group,dc=example,dc=com";

# Search params
$scope = "sub";
$filter = "memberof=$groupdn";
@returnattrs = ("member");

$upperid = "";
$result = 0;

sub Usage
{
    print STDERR<<EOF;
Usage: $0 <upper id>
EOF
    exit;
}

# load args from the command line
while ($i <= $#ARGV) {
    if ("$ARGV[$i]" eq "-help" || "$ARGV[$i]" eq "-?" || 
             "$ARGV[$i]" eq "--help") {
        &Usage;
    } else {
        $upperid = $ARGV[$i];
    }
    $i++;
}

# initializing
$ldap = Net::LDAP->new ( $fqdn, port => $port ) or die "$@";

# binding
if ($binddn eq "" && $bindpw eq "") {
    $mesg = $ldap->bind ( version => 3 );          # use for changes/edits
} else {
    $mesg = $ldap->bind ( "$binddn",           
                          password => "$binddnpw",
                          version => 3 );          # use for changes/edits
}

if ($mesg->code) {
    print "bind failed: ", ldap_error_name($mesg), "\n";
    exit 1;
}

# Add user as a member of the group
$result = $ldap->modify ( "$groupdn",
                          add => {
                              member => [ "uid=user${upperid},dc=example,dc=com", ]
                          }
                          );

if ($result->code) {
    print "modify failed: ", ldap_error_name($result), ": ", ldap_error_text($result);
    print Net::LDAP::Message::server_error($result), "\n";
}

# Do a search op for each member of large-group
for ($id = 1; $id <= $upperid; $id++) {
    my $basedn;

    $basedn = "uid=user${id},dc=example,dc=com";

    $result = $ldap->search ( base    => "$basedn",
                              scope   => "$scope",
                              filter  => "$filter",
                              attrs   =>  \@returnattrs
                              );

    if ($result->code) {
        print "search failed: ", ldap_error_name($result), ": ", ldap_error_text($result);
        print Net::LDAP::Message::server_error($result), "\n";
    }
}

# Unbind
$ldap->unbind;
