#!/usr/bin/perl
# Nearly complete clone of Umich ldapmodrdn program
#
# c.ridd@isode.com
#
# $Id: ldapmodrdn,v 1.1 2003/06/09 12:29:42 gbarr Exp $
#
# $Log: ldapmodrdn,v $
# Revision 1.1  2003/06/09 12:29:42  gbarr
# Depend in MakeMaker to fixup the #! line of installed scripts
#
# Revision 1.2  2000/07/30 21:03:50  gbarr
# *** empty log message ***
#
# Revision 1.1  1999/01/11 08:39:12  cjr
# Initial revision
#
#

use strict;
use Carp;
use Net::LDAP;
use vars qw($opt_n $opt_v $opt_r $opt_c $opt_d $opt_D $opt_w $opt_h $opt_p
	    $opt_3);
use Getopt::Std;

die "Usage: $0 [options] dn rdn\
where:\
    dn          Distinguished names of entry to modify\
    rdn         New Relative Distinguished name of entry\
options:\
    -n          show what would be done but don\'t actually change entries\
    -v          run in verbose mode (diagnostics to standard output)\
    -r          remove old RDN values from the entry\
    -c          continue after any modrdn errors\
    -d level    set LDAP debugging level to \'level\'\
    -D binddn   bind dn\
    -w passwd   bind passwd (for simple authentication)\
    -h host     ldap server\
    -p port     port on ldap server\
    -3          connect using LDAPv3, otherwise use LDAPv2\n" unless @ARGV;

getopts('nvcd:D:w:h:p:3');

$opt_h = 'nameflow.dante.net' unless $opt_h;

my %newargs;

$newargs{port} = $opt_p if $opt_p;
$newargs{debug} = $opt_d if $opt_d;

dumpargs("new", $opt_h, \%newargs) if ($opt_n || $opt_v);
my $ldap;

unless ($opt_n) {
    $ldap = Net::LDAP->new($opt_h, %newargs) or die $@;
}

#
# Bind as the desired version, falling back if required to v2
#
my %bindargs;
$bindargs{dn} = $opt_D if $opt_D;
$bindargs{password} = $opt_w if $opt_w;
$bindargs{version} = $opt_3 ? 3 : 2;

if ($bindargs{version} == 3) {
    dumpargs("bind", undef, \%bindargs) if ($opt_n || $opt_v);
    unless ($opt_n) {
	$ldap->bind(%bindargs) or $bindargs{version} = 2;
    }
}

if ($bindargs{version} == 2) {
    dumpargs("bind", undef, \%bindargs) if ($opt_n || $opt_v);
    unless ($opt_n) {
	$ldap->bind(%bindargs) or die $@;
    }
}

my %modargs;
$modargs{dn} = $ARGV[0];
$modargs{newrdn} = $ARGV[1];
$modargs{deleteoldrdn} = $opt_r ? 1 : 0;

if ($opt_n || $opt_v) {
    dumpargs("moddn",undef,\%modargs);
}
unless ($opt_n) {
    $ldap->moddn(%modargs) or die $@;
}

if ($opt_n || $opt_v) {
    print "unbind()\n";
}
unless ($opt_n) {
    $ldap->unbind() or die $@;
}

sub dumpargs {
    my ($cmd,$s,$rh) = @_;
    my @t;
    push @t, "'$s'" if $s;
    map {
	my $value = $$rh{$_};
	if (ref($value) eq 'ARRAY') {
	    push @t, "$_ => [" . join(", ", @$value) . "]";
	} else {
	    push @t, "$_ => '$value'";
	}
    } keys(%$rh);
    print "$cmd(", join(", ", @t), ")\n";
}
