#!/usr/local/bin/perl

#  Licensed to the Apache Software Foundation (ASF) under one
#  or more contributor license agreements.  See the NOTICE file
#  distributed with this work for additional information
#  regarding copyright ownership.  The ASF licenses this file
#  to you under the Apache License, Version 2.0 (the
#  "License"); you may not use this file except in compliance
#  with the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

# argv[0] = action: up/down
# argv[1] = vip: xxx.xxx.xxx.xxx
# argv[2] = rmserver.cfg

$action = $ARGV[0];
$vip = $ARGV[1];
$rmserver_cfg = $ARGV[2];
$new_rmserver_cfg = "$rmserver_cfg.new";

open(RMSERVER_CFG, $rmserver_cfg) || die "Error: cannot open $rmserver_cfg!\n";
open(RMSERVER_CFG_NEW,
     "> $new_rmserver_cfg") || die "Error: cannot open $new_rmserver_cfg!\n";

if ($action eq "up") {
    $no_change = 0;
} else {
    $no_change = 1;
}
$inside_ips = 0;
$i = 0;

while (<RMSERVER_CFG>) {
    if ($inside_ips) {
       while (!/^.*<\/List>.*$/) {
            if (/^.*<Var Address_(\d+)="(.+)"\/>.*$/) {
                $VIP[$i] = $2;
                $i++;
                if ($2 eq $vip) {
                    $no_change = !$no_change;
                }
            }
            $_ = <RMSERVER_CFG>;
        }
        $inside_ips = 0;
    } elsif (/^.*<List Name="IPBindings">.*$/) {
        $inside_ips = 1;
    } else {
        print RMSERVER_CFG_NEW $_;
    }
}
close(RMSERVER_CFG);

# Two scenarios when we don't need to do any work:
#   1. up: new vip already on list
#   2. down: vip to remove not on list
if (!$no_change) {
    $i = 1;
    if ($action eq "up") {
        print RMSERVER_CFG_NEW "<List Name=\"IPBindings\">\n";
        foreach $old_vip (@VIP) {
	    if ($old_vip ne "127.0.0.1") {
                print RMSERVER_CFG_NEW "  <Var Address_$i=\"$old_vip\"/>\n";
                $i++;
            }
        }
        print RMSERVER_CFG_NEW "  <Var Address_$i=\"$vip\"/>\n";
        $i++;
        print RMSERVER_CFG_NEW "  <Var Address_$i=\"127.0.0.1\"/>\n";
        print RMSERVER_CFG_NEW "</List>\n";
    } else {
	if ($#VIP > 1) {
            print RMSERVER_CFG_NEW "<List Name=\"IPBindings\">\n";
            foreach $old_vip (@VIP) {
                if ($vip ne $old_vip) {
                    print RMSERVER_CFG_NEW "  <Var Address_$i=\"$old_vip\"/>\n";
                    $i++;
                }
	    }
            print RMSERVER_CFG_NEW "</List>\n";
        }
    }
    close(RMSERVER_CFG_NEW);

    rename $new_rmserver_cfg, $rmserver_cfg;
} else {
    close(RMSERVER_CFG_NEW);
}

unlink $new_rmserver_cfg;

exit(0);
