#!/usr/bin/perl5.10.1

use warnings;
use strict;

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

my %opts;
GetOptions( \%opts,  "perm", "ip=s", "help" );
unless (  $opts{ip} && ( $opts{ip} =~ /\d+\.\d+\.\d+\.\d+/ ) ) {
  print "You must specify an ip address.\n\n";
  usage();
  exit;
}


add_to_ipset($opts{ip}, $opts{perm}) or die "Failed to add " . $opts{ip} . " to ipset.";
if ( $opts{perm} ) {
  add_to_ipdrop($opts{ip}) or die "Added to ipset, but failed to add to ipdrop_local!";
}

my $date = DateTime->now();
$date->set_time_zone( 'America/Chicago' );
my $user = $ENV{'RUSER'} || 'unknown';
my $line = '[' . $date->mdy . ':' . $date->hms . '] ' . $user . ' ';
$line .= "PERMANENTLY " if ( $opts{perm} );
$line .= "blocked $opts{ip}\n";

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

sub add_to_ipset {
  my $ip = shift;
  my $perm = shift || undef;
  my $ipset = 'ipdrop-temp';
  $ipset = 'ipdrop' if ( $perm );

  my ($chld_in, $chld_out, $chld_err);
  use Symbol 'gensym'; $chld_err = gensym;
  my $pid = open3($chld_in, $chld_out, $chld_err, '/usr/sbin/ipset', '-exist', 'add', $ipset, $ip);
  my @out = <$chld_out>;
  my @err = <$chld_err>;
  close $chld_in;
  close $chld_out;
  close $chld_err;
  waitpid ( $pid, 0 );
  my $stat = $? >> 8;
  return undef unless ( $stat == 0 );
  return 1; 
}

sub add_to_ipdrop {
  my $ip = shift;
  open my $fh, '<', '/etc/firewall/conf/ipdrop_global';
  my @ips = <$fh>;
  close $fh;
  chomp @ips;
  if ( grep { /^$ip$/ } @ips ) {
    print "$ip already exists in ipdrop_global\n";
    exit 2;
  }

  @ips = ();
  open $fh, '<', '/etc/firewall/conf/ipdrop_local';
  @ips = <$fh>;
  close $fh;
  chomp @ips;

  # as long as we're going to rewrite ipdrop_local, we may as well clear dupes
  my %temp = map { $_ => 1 } @ips;
  @ips = keys %temp;

  if ( grep { /^$ip$/ } @ips ) {
    print "$ip already exists in ipdrop_local\n";
    exit 2;
  }

  push @ips, $ip;
  open $fh, '>', '/etc/firewall/conf/ipdrop_local.new';
  print $fh "$_\n" for @ips;
  close $fh;
  rename '/etc/firewall/conf/ipdrop_local.new', '/etc/firewall/conf/ipdrop_local';
}

sub usage {
  print "blockip - blocks an IP from connecting to the server\n";
  print "\t--ip   - IP address to block\n";
  print "\t--perm - Block IP address permanently\n\n";
  print "Default is to block the IP address for 2 hours. Adding --perm will permanently block the IP address and add it to ipdrop_local.\n";
}
