#!/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.
#

#
# Total squid 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 $traffic = 0;
# used to fix bad counter
my $bad_counter = 0;

# 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 ($_ =~ /size: (\d+)/) {
            $traffic = int($1);
        }
        # cleanup total from bad counters
        if ($_ =~ /^tag_none/ || $_ =~ /^tag_miss/ || $_ =~ /^tcp_mem_hit/) {
            my ($host, $bytes, $conn, $other) = split(/\s+/, $_);
            $bad_counter += int($bytes);
        }
    }
    close($fh);
}

print encode_json({
        minerId => "squidtraffic-counter",
        type => "counter",
        trendType => "percentage",
        unit => "bytes",
        aggregationType => "sum",
        value => $traffic-$bad_counter,

    });
