#!/usr/bin/perl
use Sys::Hostname;
use LWP::UserAgent;
use Digest::MD5 qw(md5_hex);
use DBI;
use strict;
use warnings;
my $db = "/opt/eig_linux/etc/marked_phishing_domains.sqlite";
my $banfile = "/opt/mod_security/domain_blacklist.txt";
my $hostname = hostname();
my $time = time;
my %banned;

my $dbh = DBI->connect("dbi:SQLite:dbname=$db", undef, undef, { RaiseError => 1 });
$dbh->do(<<'SQL');
CREATE TABLE IF NOT EXISTS domains (
	domain TEXT NOT NULL,
	owner TEXT NOT NULL,
	user TEXT NOT NULL,
	added INT NOT NULL, -- epoch time, when added to this db
	PRIMARY KEY (domain)
-- what if same domain added multiple times under different users?
-- then it'll instantly be blocked with no additional notice. not a big deal.
-- 99%+ of the time this is ideal
);
SQL

my $key = md5_hex("-a9swdfjzosdkjxx:$hostname");
my $ua = LWP::UserAgent->new;
$ua->ssl_opts(verify_hostname => 0);
$ua->timeout(10);
my $req = HTTP::Request->new(GET => "https://192.185.0.115/~sec/signals/suspectdomain.nim?host=$hostname&key=$key");
my $res = $ua->request($req);
die "Request failed: ".$res->status_line unless $res->is_success;
$dbh->do('BEGIN TRANSACTION');
for my $line (split /\n/, $res->content) {
	my ($domain, $owner, $user, $marked) = split / /, $line;
	die "failed to 'parse' line: $line" unless defined($domain) && defined($owner) && defined($user);
	$dbh->do('INSERT OR IGNORE INTO domains VALUES (?, ?, ?, ?)', {}, $domain, $owner, $user, $time);
	$banned{$domain} = 1;
}
$dbh->do('COMMIT');
$dbh->disconnect();

my $fresh = keys(%banned);
open my $rbans, '<', $banfile or die "failed to open $banfile for reading : $!";
while (defined(my $line = <$rbans>)) {
	chomp $line;
	$fresh-- if exists $banned{$line};
	$banned{$line} = 1;
}
close $rbans;

exit unless $fresh;

open my $wbans, '>', "$banfile.new.$time" or die "failed to open $banfile for writing : $!";
for (sort keys %banned) {
	print {$wbans} "$_\n";
}
close $wbans and rename "$banfile.new.$time" => $banfile;
