# BEGIN COPYRIGHT BLOCK
# Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
# Copyright (C) 2005 Red Hat, Inc.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#

# END COPYRIGHT BLOCK
#!../../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);

