#!/usr/bin/perl

#
# Copyright (C) 2020 Nethesis S.r.l.
# http://www.nethesis.it - info@nethesis.it
#
# This script is part of Dante.
#
# Dante is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# Dante is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Dante.  If not, see COPYING.
#

#
# Return blacklists statistics in JSON format
#

use strict;
use warnings;
use POSIX qw(strftime);
use JSON;
use esmith::NetworksDB;
use esmith::ConfigDB;
use File::Basename;

my $log = "/var/log/firewall.log";
my $date = strftime "%b %e", localtime;
my $yesterday = strftime "%Y%m%d", localtime(time() - (24 * 60 * 60));
my $previous_log = $log."-$yesterday";
my $previous_log_gz = $previous_log.".gz";
my $db = esmith::ConfigDB->open_ro();
my $status = $db->get_prop('blacklist', 'status') || 'disabled';

if (! -f $log || $status ne 'enabled') {
    exit 1;
}

my %sources;
my @data;

open(PIPE, "zgrep '$date' $log $previous_log $previous_log_gz 2>/dev/null | grep blacklst | grep -Eo 'SRC=([0-9]{1,3}[\.]){3}[0-9]{1,3}' | cut -d '=' -f2 | sort | uniq -c|");
while (my $row = <PIPE>) {
    $row =~ /^\s+(\d+)\s+(.*)$/;
    $sources{$2} = $1;
}
close(PIPE);


foreach (sort { $sources{$b} <=> $sources{$a} } keys %sources) {
    push(@data, {'name' => $_, 'count' => $sources{$_}});
}

print encode_json({
        minerId => basename($0),
        type => "list",
        data => \@data,
        unit => "number",
        anonymizable => JSON::true,
        aggregationType => "sum"
    });
