#!/usr/bin/perl
use Sys::Hostname;
use LWP::UserAgent;
use Digest::MD5 qw(md5_hex);
use DBI;
use strict;
use warnings;
my $hostname = hostname();
my $time = time;

my $key = md5_hex("-a9swdfjzosdkjxx:$hostname");
my $ua = LWP::UserAgent->new;
$ua->agent('attackpage-potteryreporter');
$ua->ssl_opts(verify_hostname => 0);
$ua->timeout(10);
my $req = HTTP::Request->new(GET => "https://192.185.0.115/~sec/signals/attackpage.nim?host=$hostname&key=$key");
my $res = $ua->request($req);
exit unless $res->is_success;
my %next = map { $_, 1 } grep { /\S/ } split /\n/, $res->content;

my $dbh = DBI->connect("dbi:SQLite:dbname=/opt/eig_linux/etc/attackpage.sqlite", undef, undef, { RaiseError => 1 });
$dbh->do(<<'SQL');
CREATE TABLE IF NOT EXISTS active (
        time INT NOT NULL,
        user TEXT NOT NULL,
        ticket TEXT NOT NULL,
        domain TEXT NOT NULL,
        path TEXT NOT NULL,
        UNIQUE (path)
);
SQL
my %current = map { @$_, 1 } @{$dbh->selectall_arrayref("SELECT distinct(domain) FROM active WHERE ticket='SIR-5350'")};
$dbh->disconnect();

for my $domain (keys %next) {
    next if exists $current{$domain};
    system '/root/bin/abusetool', 'warningpage', 'apply', $domain, 'SIR-5350', '1', '--quiet';
}
for my $domain (keys %current) {
    next if exists $next{$domain};
    # shouldn't be suspended anymore:
    system '/root/bin/abusetool', 'warningpage', 'remove', $domain, 'SIR-5350', '1', '--quiet';
}
