#!/usr/bin/perl -w

#
# IDENTICA a "EstadisticasClam", salvo que calcula y escribe la diferencia
# con contador_HOY.db en vez de la total de contador.db
#

use strict;

use BerkeleyDB;

my (%tablahoy,%tablatot,%tabla,@tabla);

my $FIDBHOY="/usr/local/etc/contador_HOY.db";
my $FIDBTOT="/usr/local/etc/contador.db";

sub PintaLinea
{
  my ($mens,$valor)=@_;
  print "<tr><td>$mens</td><td align=right>$valor</td></tr>\n";
}

my $timefile = (stat($FIDBHOY) )[9]  ;
my $timecheck=localtime $timefile  ;
# my $timecheck=localtime time  ;

my $titulo="ACTUAL";
if (defined $ARGV[0] and $ARGV[0] ne "") { $titulo=$ARGV[0]; }

if ($titulo ne "DIARIA") {
print <<EOH;
Content-Type: Text/HTML

EOH
  }
  
print <<EOH;
  <html>
  <head>
    <title>Estadisticas del antivirus CLAM, Universitat de Valencia</title>
  </head>
  <body>
  <h1>Estad&iacute;sticas del antivirus CLAM<br>
      ESTAD&Iacute;STICA $titulo
      </h1>
      <i>($timecheck)</i>
EOH

# Le indica al contadord que salve AHORA los contadores
open (FIFIFO,">/var/run/clamav/contador.fifo") or die;
print FIFIFO "SYNC\n";
close FIFIFO;

# Es lamentable, pero el "use BerkeleyDB"+tie es MUCHO más lento :-(

# Abre la tabla total y la tabla con el "checkpoint"
tie %tablahoy,  'BerkeleyDB::Hash', 
               -Filename => $FIDBHOY,
                 or die "***Imposible abrir $FIDBHOY: $BerkeleyDB::Error\n";
                 
tie %tablatot,  'BerkeleyDB::Hash', 
               -Filename => $FIDBTOT,
                 or die "***Imposible abrir $FIDBTOT: $BerkeleyDB::Error\n";

for ( keys %tablatot ) {
  if (defined $tablahoy{$_}) {
    $tabla{$_} = $tablatot{$_} - $tablahoy{$_};
    }
  else {
    $tabla{$_} = $tablatot{$_};
    }
  }
untie %tablatot;
untie %tablahoy;
                 

for ( sort { $tabla{$b} <=> $tabla{$a} } keys %tabla ) {
  my $nombre=$_;
  my $valor=$tabla{$nombre};
  if ($nombre eq "inicio" or
      $nombre eq "mensajes" or
      $nombre eq "virus" or
      $nombre eq "enviados" or
      $nombre eq "descartados" or
      $nombre eq "arranques" ) { next; }
  else {
    push @tabla,"$nombre:$valor";
    }
  }
print "<p>";
if (defined $tabla{inicio} ) {
  PintaLinea ("Inicio de la Estad&iacute;stica: ", $tabla{inicio} ); 
  }
print "</p><table>";

my $porcen=sprintf "%2.1f",($tabla{virus}*100)/$tabla{mensajes};

PintaLinea ("Mensajes Procesados", $tabla{mensajes}); 
PintaLinea ("Mensajes con virus",  "$tabla{virus} <td>($porcen%)</td>" ); 
PintaLinea ("... limpiados", $tabla{enviados}); 
PintaLinea ("... descartados", $tabla{descartados}); 
PintaLinea ("Arranques Milter", $tabla{arranques}); 
  
print "</table><h2>-----------</h2>\n<table>"; 

for (@tabla) {
  my ($nombre,$valor)=split ':';
  if ($valor ne 0) {  PintaLinea ($nombre, $valor); }
  }
  
print <<EOH;
  </table>
  </body>
  </html>
EOH
  

  
