#!/usr/bin/env perl

use warnings;
use DateTime;

%months = ('Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4,
	   'May' => 5, 'Jun' => 6, 'Jul' => 7, 'Aug' => 8,
	   'Sep' => 9, 'Oct' => 10, 'Nov' => 11, 'Dec' => 12);

my ($ip,$day,$month,$year,$hour,$min,$sec,$bytes);

while (<>) {
    chomp;
#	print STDERR "$i\n";
    if ($_ =~ /POST \/nebulous HTTP\/1.1/) { # This is a nebulous query
	s/(\d+?\.\d+?\.\d+?\.\d+?) - - \[(\d\d)\/(\w\w\w)\/(\d\d\d\d)\:(\d\d)\:(\d\d)\:(\d\d).*\] "POST \/nebulous HTTP\/1.1" 200 (\d+?)/$1 $2 $3 $4 $5 $6 $7 $8/;
	($ip,$day,$month,$year,$hour,$min,$sec,$bytes) = split / /;
	$month = $months{$month};
	$type  = size_to_type($bytes);
	count_it($type,$year,$month,$day,$hour,$min,$sec);
    }
}

print "#epoch\t";
foreach $tag (keys %tags) {
    print "$tag\t";
}
print "\n";
foreach $time (sort {$a <=> $b} (keys %data)) {
    print "$time\t";
    foreach $tag (sort (keys %tags)) {
        unless (exists($data{$time}{$tag})) {
            $data{$time}{$tag} = 0;
        }
        print "$data{$time}{$tag}\t";
    }
    print "\n";
}

sub size_to_type {
    my $bytes = shift;
    if ($bytes == 488) { # == 488
	return("delete");
    }
    elsif ($bytes > 1800) { # 1577 + 3*ext_key for stat, 1597 + 3*ext_key for delete
	return("failure_stat");
    }
    elsif ($bytes > 850) {  # 819 + ext_key for stat
	return("stat");
    }
    elsif ($bytes > 650) {  # 600 + ext_key
	return("find_instance");
    }
    elsif ($bytes > 575) { # 526 + ext_key
	return("create");
    }
#    else {
#	print "$bytes\n";
#    }
    return("unknown");
}

sub count_it {
    my $tag = shift;
    my $year = shift;
    my $month = shift;
    my $day = shift;
    my $hour = shift;
    my $min = shift;
    my $sec = shift;
    
    # Truncate to hours;
    $sec = 0;
    $min = int($min / 10) * 10;
#    $min = 0;
    my $dt = DateTime->new( year => $year, month => $month, day => $day, hour => $hour, minute => $min, second => $sec);
    my $time = $dt->epoch;

    $data{$time}{$tag} += 1;
    $tags{$tag} = 1;
}
