1#!/usr/bin/perl
2# Nearly complete clone of Umich ldapdelete program
3#
4# c.ridd@isode.com
5#
6# $Id: ldapdelete,v 1.1 2003/06/09 12:29:42 gbarr Exp $
7#
8# $Log: ldapdelete,v $
9# Revision 1.1  2003/06/09 12:29:42  gbarr
10# Depend in MakeMaker to fixup the #! line of installed scripts
11#
12# Revision 1.2  2000/07/30 21:03:50  gbarr
13# *** empty log message ***
14#
15# Revision 1.1  1999/01/11 08:38:46  cjr
16# Initial revision
17#
18#
19
20use strict;
21use Carp;
22use Net::LDAP;
23use vars qw($opt_n $opt_v $opt_c $opt_d $opt_D $opt_w $opt_h $opt_p $opt_3);
24use Getopt::Std;
25
26die "Usage: $0 [options] dns\
27where:\
28    dns         Distinguished names of entries to delete\
29options:\
30    -n          show what would be done but don\'t actually delete\
31    -v          run in verbose mode (diagnostics to standard output)\
32    -c          continue after any delete errors\
33    -d level    set LDAP debugging level to \'level\'\
34    -D binddn   bind dn\
35    -w passwd   bind passwd (for simple authentication)\
36    -h host     ldap server\
37    -p port     port on ldap server\
38    -3          connect using LDAPv3, otherwise use LDAPv2\n" unless @ARGV;
39
40getopts('nvcd:D:w:h:p:3');
41
42$opt_h = 'nameflow.dante.net' unless $opt_h;
43
44my %newargs;
45
46$newargs{port} = $opt_p if $opt_p;
47$newargs{debug} = $opt_d if $opt_d;
48
49dumpargs("new", $opt_h, \%newargs) if ($opt_n || $opt_v);
50my $ldap;
51
52unless ($opt_n) {
53    $ldap = Net::LDAP->new($opt_h, %newargs) or die $@;
54}
55
56#
57# Bind as the desired version, falling back if required to v2
58#
59my %bindargs;
60$bindargs{dn} = $opt_D if $opt_D;
61$bindargs{password} = $opt_w if $opt_w;
62$bindargs{version} = $opt_3 ? 3 : 2;
63
64if ($bindargs{version} == 3) {
65    dumpargs("bind", undef, \%bindargs) if ($opt_n || $opt_v);
66    unless ($opt_n) {
67	$ldap->bind(%bindargs) or $bindargs{version} = 2;
68    }
69}
70
71if ($bindargs{version} == 2) {
72    dumpargs("bind", undef, \%bindargs) if ($opt_n || $opt_v);
73    unless ($opt_n) {
74	$ldap->bind(%bindargs) or die $@;
75    }
76}
77
78foreach (@ARGV) {
79    if ($opt_n || $opt_v) {
80	print "delete('$_')\n";
81    }
82    unless ($opt_n) {
83	$ldap->delete($_) or die $@;
84    }
85}
86
87if ($opt_n || $opt_v) {
88    print "unbind()\n";
89}
90unless ($opt_n) {
91    $ldap->unbind() or die $@;
92}
93
94sub dumpargs {
95    my ($cmd,$s,$rh) = @_;
96    my @t;
97    push @t, "'$s'" if $s;
98    map {
99	my $value = $$rh{$_};
100	if (ref($value) eq 'ARRAY') {
101	    push @t, "$_ => [" . join(", ", @$value) . "]";
102	} else {
103	    push @t, "$_ => '$value'";
104	}
105    } keys(%$rh);
106    print "$cmd(", join(", ", @t), ")\n";
107}
108