#!../../install/perl -w

# change the IP address of the the admin server in the configuration

die "Usage: admin_ip.pl <Directory Manager's DN> <Directory Manager's password> 
<old IP> <new IP> [port #]\n" unless (($#ARGV >= 2) && ($#ARGV <= 4));

$dirmgr = $ARGV[0];
$passwd = $ARGV[1];
$oldIPaddr = $ARGV[2];
$newaddr = $ARGV[3];
$port = 389;
$port = $ARGV[4] if ($ARGV[4]);

$adminconfig = "../../admin-serv/config/";
$ldapsearch = "./ldapsearch";
$ldapmodify = "./ldapmodify";
$baseobject = "o=NetscapeRoot";
$query = "(&(&(cn=configuration)(objectclass=nsConfig))(nsserveraddress=\"$oldIPaddr\"))";
$dn = "";
$oldaddr = "";

$/ = ""; # enable paragraph mode

# Find the old IP address in the directory
open (LDAP, "$ldapsearch -p $port -b $baseobject -D \"$dirmgr\" -w $passwd \"$query\" |");
while (<LDAP>) {
  s/\n //g;
  if (/\nnsserveraddress: (.*)\n/) {
    $oldaddr = $1;
    print "Old IP in directory: $oldaddr\n";
  }
  if (/^dn: (.*)\n/) {
    $dn = $1;
    print "DN: $dn\n";

# Update the IP address stored in the configuration directory
    open (LDAP2, "| $ldapmodify -p $port -D \"$dirmgr\" -w $passwd");
    print LDAP2 "dn: $dn\n";
    print LDAP2 "changetype: modify\n";
    print LDAP2 "replace: nsserveraddress\n";
    print LDAP2 "nsserveraddress: $newaddr\n";
    close (LDAP2);
  }
}
close (LDAP);

# Verify that the IP address has been updated
# $testaddr = "";
# pen (LDAP, "$ldapsearch -p $port -b $baseobject -D \"$dirmgr\" -w $passwd \"$query\" |");
# while (<LDAP>) {
#   if (/\nnsserveraddress: (.*)\n/) {
#     $testaddr = $1;
#     if ($testaddr eq $newaddr) {
#       print "The IP address in the directory was updated\n";
#     } else {
#       print "Error updating IP address in the directory!\n";
#     }
#   }
# }

# Update the admin config file
$newconfig=$adminconfig . "local.conf";
$oldconfig = $adminconfig . "local.conf.old";
rename $newconfig, $oldconfig;
open (OLD, "<" . $oldconfig);
open (NEW, ">" . $newconfig);
print "oldaddr: $oldaddr\n";
print "newaddr: $newaddr\n";
while (<OLD>) {
  s/$oldaddr/$newaddr/g;
  print NEW;
}
close(OLD);
close(NEW);

