#!/usr/bin/perl

use warnings;
use strict;

use Getopt::Long;
use IPC::Open3;
use Config::General;
use DateTime;
use Data::Dumper;

my %opts;
my ($ip, $port, $tick, $help);
GetOptions(
  "ip=s"        => \$ip,
  "port=s"      => \$port,
  "--ticket=s"  => \$tick,
  "help"        => \$help,
);

unless (  $ip && ( $ip =~ /\d+\.\d+\.\d+\.\d+/ ) && $port && ($port =~ /\d+/) ) {
  print "You must specify an ip address and port.\n\n";
  usage();
  exit;
}

unless ( `/sbin/ip a` =~ /$ip/ ) {
  print "IP address ($ip) does not exist on this server.\n\n";
  usage();
  exit;
}

add_to_ports_whitelist($ip, $port);

# Handle restart
restart_if_needed();

my $date = DateTime->now();
$date->set_time_zone( 'America/Chicago' );
my $user = $ENV{'RUSER'} || 'unknown';
my $ticket = $tick || 'not provided';
my $line = '[' . $date->mdy . ':' . $date->hms . '] ' . $user . ' ';
$line .= "added $ip:$port to ports_whitelist for ticket: $ticket\n";

open my $fh, '>>', '/var/log/firewall-modification.log' or die "Failed to open log file.";
print $fh $line;
close $fh;


sub add_to_ports_whitelist {
  my ($ip, $port) = @_;
  my $conf = '/etc/firewall/conf/ports_whitelist.conf';
  my @lines;

  if ( -f $conf ) {
    @lines = slurp($conf) or die "Cannot open conf $conf: $!\n";
    # Ensure we're using correct syntax for Config::Merge to work
    map {s/:/=/g; } @lines;
  }

  # Let's not add duplicates
  die "Existing entry $ip=$port in $conf\n" if (grep /^$ip=$port$/, @lines);

  push @lines, "$ip=$port";

  open my $fh, '>', "$conf.new" or die "Cannot open $conf.new for writing: $!";
  print $fh join ("\n", @lines) . "\n";
  close $fh;

  rename "$conf.new", "$conf" or die "Cannot move new config file to $conf: $!\n";
}

sub slurp {
  my $self = shift;
  return split /\n/, do { local ( @ARGV, $/ ) = $self; <> };
}

sub restart_if_needed {
  print "restarting firewall .. ";
  my ($chld_in, $chld_out, $chld_err);
  use Symbol 'gensym'; $chld_err = gensym;
  my $pid = open3($chld_in, $chld_out, $chld_err, '/etc/init.d/firewall', 'restart');
  my @out = <$chld_out>;
  my @err = <$chld_err>;
  close $chld_in;
  close $chld_out;
  close $chld_err;
  waitpid ( $pid, 0 );
  my $stat = $? >> 8;
  if ( $stat == 0 ) {
    print "done\n";
  }
  else {
    print "Failed restarting firewall. Manually check this!\n";
  }
}

sub usage {
  print "bh-openport - opens a inbound port to a specific ip address\n";
  print "\t--ip - ip to whitelist\n";
  print "\t--port - port to whitelist\n";
  print "\t--ticket - ticket id\n\n";
}
