#!/usr/bin/perl

use strict;
use YAML qw( LoadFile );
use Data::Dumper;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use BackupServer;

my $bk = new BackupServer;

my $run = 1 if ( $ARGV[0] eq 'run' );

my $ports_allowed = "22,111,2049,3260,9279";
my $config_dir = "/opt/eig_linux/conf";

if ($bk->get_config_value('puppet_master') eq 'henson'){
    print "This script is deprecated for henson puppet clients. Please run puppet instead to update the firewall.\n";
    exit 0;
}

my %hosts;
my $config = $bk->get_partitions();
foreach my $entry ( keys %$config ) {
	$hosts{$$config{$entry}{backnetip}} = 1;
}
my $current;
if ( -f "/etc/sysconfig/iptables" ) {
	open (CURRENT, "</etc/sysconfig/iptables");
	foreach my $line (<CURRENT>) {
		$current .= $line;
	}
	close CURRENT;
}
my $new;
open (TEMPLATE, "<$config_dir/iptables.template") || die "Failed to load $config_dir/iptables.template: $!\n";
foreach my $line (<TEMPLATE>) {
	if ( $line =~ m/^<clients>$/ ) {
		$new .= "# Start Client Allow Rules\n";
		foreach my $host ( keys %hosts ) {
			$new .= "-A INPUT -s $host -m state --state NEW -p tcp -m multiport --dports $ports_allowed -j ACCEPT\n";
		}
		$new .= "# End Client Allow Rules\n";
	} else {
		$new .= $line;
	}
}
close TEMPLATE;

if ( $new ne $current ) {
	print "Need to update iptables\n";
	if ( $run ) {
        	mkdir "$config_dir/backups" if ( !-d "$config_dir/backups" );
		my $time = time();
		system("cp -a /etc/sysconfig/iptables $config_dir/backups/iptables.$time") == 0 || die "Failed to backup iptables to $config_dir/backups/iptables.$time: $!\n";
		open(NEW, ">/etc/sysconfig/iptables");
		print NEW $new;
		close NEW;
		system("service iptables restart");
	} else {
		print "New config would be:\n\n$new\n\n";
		exit 0;
	}
}
exit 2;
