#!/usr/bin/perl -w
# ------------------------------------------------------------
# script:  ldapmodgroup.pl
# Author:  Brad Marshall (bmarshal@pisoftware.com)
# License: GPL
# Date:    20000203
#
# Purpose: Modifies a group in LDAP
#
# Copyright (c) 2000 Plugged In Software Pty Ltd.  All rights reserved.

# TODO

use strict;
use Net::LDAP;
use Getopt::Std;
use Term::ReadKey;

use vars qw($opt_r $opt_a);

my($user, $group);
my($result);

my($root) = "dc=pisoftware,dc=com";
my($host) = "ldap.staff.plugged.com.au";
my $exception = 0;

$SIG{'INT'} = $SIG{'QUIT'} = $SIG{'HUP'} = sub { $exception=1; };

getopts('ra');

if (! $ARGV[0]) {
    print "$0: $0 [-r username] [-a username] group\n";
	print "\t-r removes the username, -a adds the username\n";
    exit 1;
}

if ($ARGV[0]) {
	$user = $ARGV[0];
} else {
	die "Sorry, you must specify a username";
}
if ($ARGV[1]) {
	$group = $ARGV[1];
} else {
	die "Sorry, you must specify a group name";
}

&check;

my($groupdn) = "cn=$group,ou=Group,$root";

my($ldap) = Net::LDAP->new($host) or die "Can't bind to ldap: $!\n";

my($manager) = "cn=Manager,$root";
print "$manager\n";

print "Please enter LDAP Managers password: ";

ReadMode 'noecho';
my $password = ReadLine 0;
chomp $password;
ReadMode 'normal';
print "\n";

$ldap->bind(
            dn       => $manager,
            password => $password,
        );

if ($exception) {
	die "Caught a signal";
} else {

	if ($opt_r) {
		# We're removing the user
		print "We're removing the user\n";
		$ldap->modify( $groupdn, delete => { memberuid => $user } );		
	} else {
		# We're adding the user
		print "We're adding the user\n";
		$ldap->modify( $groupdn, add => { memberuid => $user } );		
	}
	#$result->code && warn "failed to add entry: ", $result->error ;
};

sub check {
	my($userfilter,$groupfilter);
	my(@userentries, @groupentries);

	my($ldap) = Net::LDAP->new($host) or die "Can't bind to ldap: $!\n";

	$ldap->bind;

	# check $user
	$userfilter = "uid=$user";
	my($usermesg) = $ldap->search( base => $root,
                                   filter => $userfilter
                                 );

	@userentries = $usermesg->entries;
	if ($#userentries) {
		die "Username $user doesn't appear to exist"
	}
	$usermesg->code && die $usermesg->error;

	# check $group
	$groupfilter = "cn=$group";
	my($groupmesg) = $ldap->search( base => $root,
                                    filter => $groupfilter
                                  );

	@groupentries = $groupmesg->entries;
	if ($#groupentries) {
		die "Group $group doesn't appear to exist"
	}

	$groupmesg->code && die $groupmesg->error;
}

