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

# TODO
#   Check if any users have this as a default group?

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

use vars qw($opt_g);

my($gidnumber);
my($gidref);
my($cn);
my($dn);
my($result);
my($entry);

my($root) = "dc=pisoftware,dc=com";
my($host) = "ldap.staff.plugged.com.au";
my(@objectclass) = [ 'posixGroup', 'top' ];
my $exception = 0;

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

getopts('g:');

# groupadd [-g gid [-o]] [-r] [-f] group

if (! $ARGV[0]) {
    print "$0: $0 group\n";
    exit 1;
}


if ($ARGV[0]) {
	$cn = $ARGV[0];
	if ($cn !~ /[a-z]{2,8}/) {
		die "Sorry, group name must consist solely of letters and be between 2 and 8 characters.";
	}
} else {
	die "Sorry, you must specify a group name";
}

$dn = &findgid;

#dn: cn=support,ou=Group,dc=pisoftware,dc=com
#objectclass: posixGroup
#objectclass: top
#cn: support
#gidnumber: 140

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";

print "\$dn = $dn\n";

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

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

if ($exception) {
	die "Caught a signal";
} else {
	$result = $ldap->delete ( $dn );
	$result->code && warn "failed to delete entry: ", $result->error ;
};


# Subroutines

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

	$ldap->bind;

	my($mesg) = $ldap->search( base => $root,
                               filter => '(objectclass=posixGroup)'
                             );

	$mesg->code && die $mesg->error;

	foreach $entry ($mesg->entries) {
		my($tmpcn) = $entry->get('cn')->[0];
		#print "\$tmpcn = $tmpcn\n";
		#my($tmpnum) = $entry->get('gidnumber');
		#print "$cn $tmpcn\n";
		if ($cn eq $tmpcn) {
			#print "Found it - \$tmpcn = $tmpcn\n";
			my($tmpdn) = $entry->dn;
			return $tmpdn;
		}
	}
	die "Sorry, can't find the group you want to delete.";
}
