#! /usr/local/bin/perl -w

use DateTime;
use Getopt::Std;
use PS::IPP::Config;


$opt{S} = 0;
getopts('SD:',\%opt);

my $datestring;
if (exists($opt{D})) {
    $datestring = $opt{D};
}
else {
    my @lt = gmtime;
    my $dt = DateTime->now;
    $dt->subtract( days => $lt[6] );
    $datestring = $dt->ymd;
}

@files = sort ( split /\n/, `neb-ls -p neb:///ipp_diskspace/${datestring}/%neb_usage.dat`);

foreach $f (@files) {
    $volume = $f;
    $volume =~ s/.*://;
    $volume =~ s/.neb_usage.dat//;
    open(F,$f);
    while(<F>) {
	chomp;
	($stage,$product,$count,$size) = split /\s+/;
	$what = "${stage}_${product}";
	$num{$volume}{$what} = $count;
	$vol{$volume}{$what} = $size;
	
	$sum{$volume} += $size;
	$sizes{$what}   += $size;
	$counts{$what}  += $count;
    }
    close(F);
}
foreach $v (keys %sum) {
    foreach $w (keys %sizes) {
	unless (exists($vol{$v}{$w})) {
	    $num{$v}{$w} = 0;
	}
	unless (exists($vol{$v}{$w})) {
	    $vol{$v}{$w} = 0;
	}
    }
}

$sep    = '||';
$presep = '||';

if ($opt{S} == 0) {
    print "${presep}Volume${sep}";
    foreach $w (sort (keys %sizes)) {
	print "$w$sep";
    }
    print "\n";
    foreach $v (sort (keys %sum)) {
	print "${presep}${v}${sep}";
	foreach $w (sort (keys %sizes)) {
	    $val = $vol{$v}{$w} / 1024 / 1024 / 1024;
	    printf "%.2f%s",$val,$sep;
	}
	$val = $sum{$v} / 1024 / 1024 / 1024;
	printf "%.2f%s",$val,$sep;
	print "\n";
    }
    my $dt = DateTime->now;
    $date = $dt->ymd;
    print "${presep}${date}${sep}";
    foreach $w (sort (keys %sizes)) {
	$val = $sizes{$w} / 1024 / 1024 / 1024;
	printf "%.2f%s",$val,$sep;
    }
    print "\n";
}
else {
    my $ipprc = PS::IPP::Config->new("GPC1");
    my $nebcon = $ipprc->nebulous();

    my $outfile = "neb:///ipp_diskspace/${datestring}/summary.dat";
    my $out_fh;
    if ($ipprc->file_exists($outfile)) {
	my $S_file = $ipprc->file_resolve($outfile);
	open($out_fh,">$S_file");
    }
    else {
	$out_fh = $ipprc->file_create_open($outfile);
    }
    foreach $w (sort (keys %sizes)) {
	$val = $sizes{$w} / 1024 / 1024 / 1024;
	$v2  = $counts{$w};
	print $out_fh "$w $val $v2\n";
    }
    close($out_fh);
}



