#!/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 $hostname = hostname();
my $time = time;
my $yesterday = $time - (24 * 3600);
my $fresh;

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(60);
my $req = HTTP::Request->new(GET => "https://192.185.0.115/~sec/suspdomains/amievil.cgi?host=$hostname&key=$key");
my $res = $ua->request($req);
$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);
	$fresh = 1 if $marked > $yesterday;
	$dbh->do('INSERT OR IGNORE INTO domains VALUES (?, ?, ?, ?)', {}, $domain, $owner, $user, $time);
}
$dbh->do('COMMIT');
$dbh->disconnect();
if ($fresh) {
	utime $time, $time, "/var/cpanel/ssl/apache_tls/", "/etc/cpanel/proxy_conf";
}
