#!/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 File::Basename;
use esmith::ConfigDB;

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 %hours;
for (my $i=0; $i<=23; $i++) {
    $hours{sprintf("%02d",$i)} = 0;
}

open(PIPE, "zgrep '$date' $log $previous_log $previous_log_gz 2>/dev/null | grep blacklst | awk '{print \$3}' | cut -d ':' -f1 | sort | uniq -c|");
while (my $row = <PIPE>) {
    $row =~ /^\s+(\d+)\s+(.*)$/;
    $hours{$2} = int($1);
}
close(PIPE);

my @categories;
my @data;

foreach (sort keys %hours) {
    push(@categories, $_);
    push(@data, $hours{$_});
}

print encode_json({
        minerId => basename($0),
        type => "chart",
        chartType => "area",
        aggregationType => "number",
        categories => \@categories,
        anonymizable => JSON::false,
	    unit => "number",
        series => [ { name => "hours", data => \@data } ]
    });
