#!/usr/bin/perl

# Copyright (C) 1996 Friedrich Leisch

# 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, 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 file.  If not, write to the Free Software Foundation,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

# Send any bug reports to Friedrich.Leisch@ci.tuwien.ac.at

# flprstat, evaluates a logfile created by flprlog
# options: -l lowest date YYMMDD
#          -h highest date YYMMDD
#          -W usage in the last 7 days including yesterday
#          -M usage in the last calendar month
#          -s create a spreadsheet

# Written by Friedrich.Leisch@ci.tuwien.ac.at, 2.1.1996

use Getopt::Std;

do getopts('l:h:WMs');
$opt_l = "000000" unless $opt_l;
$opt_h = "999999" unless $opt_h;

if($opt_W){
    # set $opt_l to today minus one week's seconds
    ($sec,$min,$hour,$mday,$mon,$year) = localtime(time-604800);
    $opt_l = sprintf("%02d%02d%02d", $year, $mon+1, $mday);

    # set $opt_h to yesterday
    ($sec,$min,$hour,$mday,$mon,$year) = localtime(time-86400);
    $opt_h = sprintf("%02d%02d%02d", $year, $mon+1, $mday);
}
elsif($opt_M){
    ($sec,$min,$hour,$mday,$mon,$year) = localtime(time);
    if($mon==0){
	$opt_l = sprintf("%02d1201", $year-1);
	$opt_h = sprintf("%02d1231", $year-1);
    }
    else{
	$opt_l = sprintf("%02d%02d01", $year, $mon); # months in perl go
	$opt_h = sprintf("%02d%02d31", $year, $mon); # from 0 to 11 !
    }
}

if($opt_s){
    spreadsheet();
}
else{
    normal();
}    


sub normal {
    while(<>){
	($date, $time, $name, $host, $pages) = split;
	if(($date ge $opt_l) && ($date le $opt_h)){
	    $sums{$name} += $pages;
	    $total += $pages;
	}
    }
    header();
    foreach $elem (keys %sums){
	printf "  %5d %s\n", $sums{$elem}, $elem;
    }
}

sub spreadsheet {
    while(<>){
	($date, $time, $name, $host, $pages) = split;
	if(($date ge $opt_l) && ($date le $opt_h)){
	    $names{$name} = ();
	    $dates{$date} = ();
	    $$name{$date} += $pages;
	    $total += $pages;
	}
    }
    header();
    print "# ";
    foreach $n (sort(keys %names)){
	print "$n ";
    }
    print "\n";
    foreach $d (sort(keys %dates)){
	print "$d ";
	foreach $n (sort(keys %names)){
	    print $$n{$d} + 0, " ";
	}
	print "\n";
    }
}

sub header {
    print "# Printer usage: $total pages ";
    print "from $opt_l " unless ($opt_l==0);
    print "to $opt_h " unless ($opt_h==999999);
    print "\n";
}

