#!/usr/bin/perl -w

use strict;

my $dir="/backup";

my %dates;
my %hosts;
my %copys;
my %links;

opendir(DIR, $dir);
while (my $subdir=readdir(DIR)) {
    if ($subdir=~m/^[a-z]/) {
	opendir DIR2, $dir."/".$subdir;
	while (my $file=readdir(DIR2)) {
	    if ($file=~m/\.log$/) {
		&parse($subdir, $file);
	    }
	}
	closedir DIR2;
    }
}
closedir DIR;

sub parse {
    my $host=shift;
    my $log=shift;

    my $date=substr($log, 0, 10);
    my $copy=0;
    my $link=0;

    open IN, $dir."/".$host."/".$log;

    while(<IN>) {
	if (/^files copied:[ ]*[0-9]*[ ]*([0-9\.]*) ([A-Z])$/) {
	    $copy=&calc($1, $2);
	}

	if (/^files linked:[ ]*[0-9]*[ ]*([0-9\.]*) ([A-Z])$/) {
	    $link=&calc($1, $2);
	}
    }

    close IN;

    $dates{$date}=1;
    $hosts{$host}=1;
    $copys{$host.":".$date}=$copy;
    $links{$host.":".$date}=$link;
}

print "\"Host\"";
foreach my $date (sort keys %dates) {
    print ", \"$date\"";
}
print ", \"Base\"\n";

foreach my $host (sort keys %hosts) {
    my $base=0;

    print "\"$host\"";
    foreach my $date (sort keys %dates) {
	if (defined $copys{$host.":".$date}) {
	    print ", ".$copys{$host.":".$date};
	    $base=$copys{$host.":".$date} + $links{$host.":".$date};
	} else {
	    print ", 0";
	}
    }
    print ", $base\n";
}

sub calc {
    my $count=shift;
    my $fcval=shift;

    if ($fcval eq "B") {
	return int($count);
    } elsif ($fcval eq "K") {
	return int($count * 1024);
    } elsif ($fcval eq "M") {
	return int($count * 1048576);
    } elsif ($fcval eq "G") {
	return int($count * 1073741824);
    } else {
	return -1;
    }
}
