#!/usr/bin/perl

use strict;
use lib "/opt/vyatta/share/perl5/";
use XorpConfigParser;

my $orig_cfg = shift;
exit 1 if (!defined($orig_cfg));

my $xcp = new XorpConfigParser();
$xcp->parse($orig_cfg);

my $target_value;

my $lb_node = $xcp->get_node(['load-balancing', 'wan']);
if (defined($lb_node)) {
    my $lb_ih = $lb_node->{'children'};
    if (defined($lb_ih)) {
        # Iterate through the interfaces
	foreach my $interfacehealth (@$lb_ih) {
	    if ($interfacehealth->{'name'} =~ /^interface-health.*/) {
		my $lb_target = $interfacehealth->{'children'};
		my $new_target = undef;
		my $new_resptime = undef;
		if (defined($lb_target)) {
		    foreach my $target (@$lb_target) {
			if ($target->{'name'} =~ /^ping.*/) {
                            my (undef,$t) = split " ",$target->{'name'};
			    $new_target = "target $t\n\t\ttype ping\n";
			    $xcp->comment_out_node($target);
			}
                        if ($target->{'name'} =~ /^resp-time.*/) {
			    $new_resptime = $target->{'name'};
			    $xcp->comment_out_node($target);
                        }
		    }

		    #now piece together the new config
		    my $new_conf = undef;
		    if (defined $new_target && defined $new_resptime) {
			$new_conf = "{\n\t\t$new_target\t\t$new_resptime\n\t    }\n";
		    }
		    elsif (defined $new_target) {
			$new_conf = "{\n\t\t$new_target\n\t    }\n";
		    }
		    elsif (defined $new_resptime) {
			$new_conf = "{\n\t\t$new_resptime\n\t    }\n";
		    }
		    else {
			#nothing
		    }

		    if (defined $new_conf) {
			my @load_balancing_wan_interfacehealth = ('load-balancing', 'wan', $interfacehealth->{'name'}, 'test 1');
			$xcp->set_value(\@load_balancing_wan_interfacehealth, $new_conf);
		    }


		}
	    }
	}
    }
}


#look for target and build new section



###new configuration
# wan {
#     interface-health eth0 {
#         nexthop 12.12.12.12

#         test 1 {
#	    target 9.9.9.9
#            type ping
#         }

#     }
# }




###old configuration

# wan {
#    interface-health eth0 {
#	nexthop 12.12.12.12

#	target 9.9.9.9

#	}
#}


my $tmpfile = "/tmp/vyatta_migrate_wanloadbalance.$$";
open(TMPFILE, ">$tmpfile") or exit 1;
select TMPFILE;

$xcp->output(0);

close TMPFILE;
my $ret = system("mv $tmpfile $orig_cfg");
exit 1 if ($ret >> 8);

exit 0;
