#!/usr/bin/perl

#    Big Sister network monitor
#    Copyright (C) 1998-2001  Thomas Aeby
#
#    This program 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 2 of the License, or
#    (at your option) any later version.
#
#    This program 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 this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

#=============================================================================
#
$BigSister::common::Usage	  = "[-D level] [-d date] configfile";
#
#=============================================================================
@BigSister::common::options = ( "d=s" );

use lib "."; use lib "uxmon"; use lib "platforms"; 		#inslib
use BigSister::common;
proginit();

use strict;
use RotatingLog;
use Time::Local;
use Reader::Reader;
use StatusLog;
use ReportCommon;

my $dl = $BigSister::common::dl;
my ($start_time, $end_time) = ReportCommon::start_date( $BigSister::common::opt_d );
my $file = shift;

opendir( DIR, "$BigSister::common::fs{'var'}/reportdb" ) || die "cannot read $BigSister::common::fs{'var'}/reportdb: $!";
my @candidates = sort grep( /day.*\.cumu\./, readdir( DIR ) );
closedir( DIR );
my %candidates = ();

my @cumulator_classes;
{
    my %cumulators;
    foreach my $candidate (@candidates) {
	my $clone = $candidate;
	$clone =~ s/.*?\.cumu\.//;
	push( @cumulator_classes, $clone ) unless( $cumulators{$clone} );
	$cumulators{$clone} = 1;
    }
}


my @reports = ();

open( CFG, "<$file" ) || die "cannot read config file $file: $!";
while( <CFG> ) {
    chomp;
    s/\r//;
    next if( /^#/ || /^$/ );

    while( /\\$/ ) {
	s/\\$//;
	$_ .= <CFG>;
	chomp;
	s/\r//;
    }

    if( /^report[\s\t]+(.*?)[\s\t]*=(.*)$/ ) {
	my( $report, $expression ) = ($1,$2);
	unreport( $report );
	$expression =~ s/\$\{(.*?)\}/(\$value->{\"$1\"})/g;
	push( @reports, {
	    "var" => $report,
	    "expr" => $expression
	} );
    }
    elsif( /^unreport[\s\t]+(.*)$/ ) {
	unreport( $1 );
    }
    elsif( /^statistic[\s\t]+(.*?)[\s\t]*=[\s\t]*(\d+)$/ ) {
	statistic( $1, $2 );
    }
    else {
	die "file $file, line $.: unknown statement";
    }
}


sub unreport {
    my( $report ) = @_;

    for( my $i=0; $i<=$#reports; $i++ ) {
	if( $reports[$i]->{"var"} eq $report ) {
	    splice( @reports, $i, 1 );
	    last;
	}
    }
}


sub statistic {
    my( $name, $days ) = @_;

    foreach my $class (@cumulator_classes) {
	my %item_values = ();

	my( $mday, $mon, $year ) = ((localtime($start_time))[3,4,5]);
	my $outfile = sprintf( "%s/reportdb/day-%04d-%02d-%02d.statistic.%s.%s",
			$BigSister::common::fs{'var'}, $year+1900, $mon+1, $mday, $class, $name );
	open( OUT, ">$outfile" ) || die "cannot open output file $outfile: $!";

	my @files = grep( /\.cumu\.\Q$class\E$/, @candidates );
	for( my $day=$days-1; $day>=0; $day-- ) {
	    my( $mday, $mon, $year ) = ((localtime($start_time-$day*24*3600+2*3600))[3,4,5]);
	    my $datestr = sprintf( "%04d-%02d-%02d", $year+1900, $mon+1, $mday );
	    my( $file ) = grep( /^day-$datestr/, @files );
	    open( STAT, "<$BigSister::common::fs{'var'}/reportdb/$file" ) || die "cannot read statistics file $file: $!";
	    while( <STAT> ) {
		chomp;
		s/\r//;
		my( $item, $status, $duration ) = split( "," );
		unless( defined $item_values{$item} ) {
		    my $values = $item_values{$item} = {
			"Total" => 0,
			"Days" => $days,
			"offservice" => 0
		    };
		    foreach my $color (keys %BigSister::common::status_codes) {
			$values->{$color} = 0;
		    }
		}
		$item_values{$item}->{$status} += $duration;
		$item_values{$item}->{"Total"} += $duration;
	    }
	    close STAT;
	}

	foreach my $item (keys %item_values) {
	    my $value = $item_values{$item};
	    foreach my $report (@reports) {
		$value->{$report->{"var"}} = eval ($report->{"expr"});
		print OUT "$item,".($report->{"var"}).",".($value->{$report->{"var"}})."\n";
	    }
	}
	close OUT;
    }
}



sub percentage {
    my( $val, $base ) = @_;

    return( "N/A" ) if( $base == 0 );
    $val = $val/$base;
    if( $val < 1 ) {
	return( int( $val*10000 )/100 );
    }
    elsif( $val < 4 ) {
	return( int( $val*1000 )/10 );
    }
    elsif( $val < 96 ) {
	return( int( $val*1000 )/10 );
    }
    elsif( $val < 99 ) {
	return( int( $val*10000 )/100 );
    }
    return( int( $val*1000000 )/10000 );
}

