#! /usr/bin/perl

use strict;
use warnings;

use lib "/opt/vyatta/share/perl5/";
use XorpConfigParser;
use File::Copy;

my $orig_cfg = shift;
exit 1 unless $orig_cfg;

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

## Move conntrack settings to firewall branch

my $conntrack = $xcp->get_node(['system', 'conntrack']);
exit 0 unless $conntrack; # Conntrack is not configured

my $fw = $xcp->get_node(['firewall']);
$xcp->create_node(['firewall']) unless $fw;

my $conntrack_children = $conntrack->{'children'};

foreach my $child (@{$conntrack_children}) {
  my ($name, $value) = split(/ /, $child->{'name'});
  if ( $name =~ /expect-table-size/ ) {
    $xcp->set_value(['firewall', 'conntrack-expect-table-size'], $value);
  }
  elsif ( $name =~ /hash-size/ ) {
    $xcp->set_value(['firewall', 'conntrack-hash-size'], $value);
  }
  elsif ( $name =~ /table-size/ ) {
    $xcp->set_value(['firewall', 'conntrack-table-size'], $value);
  }
}

if ( $xcp->node_exists('system conntrack modules sip') ) {
  $xcp->create_node(['firewall', 'conntrack-options']);
  $xcp->move_child($xcp->get_node(['system', 'conntrack', 'modules']), $xcp->get_node(['firewall', 'conntrack-options']), 'sip')
}

$xcp->comment_out_node($conntrack);

  my $tmpname = "/tmp/vyatta_migrate_5_to_4.$$";
  open (my $tmp, '>', $tmpname)
    or die "Can't open: $tmpname: $!";

  select $tmp;
  $xcp->output(0);
  select STDOUT;
  close $tmp;

  move($tmpname, $orig_cfg)
    or die "Move $tmpname to $orig_cfg failed: $!";
}

exit 0;
