#!/usr/bin/perl

#
# Copyright (C) 2019 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.
#

#
# HostWebTrafficMiner - a Miner to collect data about host traffic
#
#
use strict;
use warnings;
use JSON;
use POSIX qw(strftime);

my $date = strftime "%Y%m%d", localtime;
my $total_file = "/var/lightsquid/$date/.total";
my @data;

# run lightparser once
if (-f "/sbin/lightparser.pl" && ! -f $total_file) {
    system("/sbin/lightparser.pl -t /var/log/squid/access.log 2>/dev/null");
}

if (! -f $total_file) {
    exit 1;
}

if (-f $total_file) {
    open(my $fh, '<', $total_file);
    while (readline($fh)) {
        if ($_ =~ /^tag_none/ || $_ =~ /^tcp_miss/ || $_ =~ /^tcp_mem_hit/ || $_ =~ /^user:/ || $_ =~ /^size/) {
            # skip SSL connections and total lines
            next;
        } else {
            my ($host, $bytes, $conn, $other) = split(/\s+/, $_);
            $bytes = int($bytes);
            next if ($bytes <= 10000) || (!$host) ;
            push(@data, {count => $bytes, name => $host});
        }
    }
    close($fh);
}

print encode_json({
        minerId => "squidsources-list",
        type => "list",
        data => \@data,
        unit => "bytes",
        anonymizable => JSON::true,
        aggregationType => "sum"
    });
