#! /usr/bin/env perl
use Tie::File;
use Sys::Hostname;
use strict;
use warnings;
my $wl = '/opt/mod_security/wprbl_whitelist.txt';
my $log = '/opt/eig_linux/log/wprbl_whitelist.log';
my $now = time;
my $hostname = hostname();

die "usage: $0 whitelist <ip>\n"
	unless @ARGV == 2 && $ARGV[0] eq 'whitelist' && $ARGV[1] =~ /^ \d+\. \d+\. \d+\. \d+ $/x;

my $ip = $ARGV[1];
(my $range = "/$ip") =~ s: \.\d+$ :.:x;

tie my @wl, 'Tie::File', $wl or die "Unable to open $wl with Tie::File : $!\n";
for (@wl) {
	next unless $range eq $_;
	die "[!] wprbl whitelist on $hostname already contains $_ (which includes $ip)\n";
}
print "[*] whitelisting 256 IPs in $range (which includes $ip)\n";
push @wl, $range;
untie @wl;
logit("$now,$hostname,$ip,@{[blacklisted() ? 'blacklisted' : 'not listed']}\n");

print "[*] gracefulling apache... (this can take a few minutes)\n";
my @out;
if ($ENV{RUSER}) { # if not called through eigsh
	system "/usr/sbin/httpd -k graceful 2>&1";
} else {
	@out = qx(/usr/sbin/httpd -k graceful 2>&1);
}
if ($?) {
	print @out, "\n";
	print "[!] failed to graceful apache! is the server OK?\n";
} else {
	print "[*] wprbl whitelist updated, on disk and for apache\n";
}

sub logit {
	open my $f, '>>', $log or warn "Failed to open $log for appending : $!";
	print {$f} $_ for @_;
	close $f;
}

sub blacklisted { qx:/usr/bin/dig @{[join(".", reverse(split /\./, $ip), "testwprbl.websitewelcome.com")]}: =~ /127/ }
