#! /usr/bin/perl -w

use strict;

my %hits = ('TCP_HIT' => 1,
            'TCP_REFRESH_HIT' => 1,
            'TCP_REF_FAIL_HIT' => 1,
            'TCP_IMS_HIT' => 1,
            'TCP_NEGATIVE_HIT' => 1,
            'TCP_MEM_HIT' => 1,
            'TCP_OFFLINE_HIT' => 1);
my %miss = ('TCP_MISS' => 1,
            'TCP_REFRESH_MISS' => 1,
            'TCP_CLIENT_REFRESH_MISS' => 1,
            'TCP_SWAPFAIL_MISS' => 1,
            'TCP_CLIENT_REFRESH' => 1,
            'TCP_SWAPFAIL' => 1,
            'TCP_IMS_MISS' => 1);

die "Usage: $0 [-v] INFILE" if ($#ARGV != 0 and !($#ARGV == 1 and $ARGV[0] eq '-v'));
my $verbose = 0;
my %types;
if ($ARGV[0] eq '-v')
{
  $verbose = 1;
  shift @ARGV;
}

open(FILE, $ARGV[0]) or die "$ARGV[0] not found.";
print "Analyzing access log...\n";

my $hit_count = 0;
my $miss_count = 0;
my $count = 0;

while (<FILE>)
{
  my @line = split(' ');
  next if $line[2] eq '255.255.255.255';
  my ($response_code) = split('/', $line[3]);
  $hit_count++     if exists $hits{$response_code};
  $miss_count++    if exists $miss{$response_code};
  $count++;
  if ($verbose)
  {
    if (!exists $types{$response_code}) { $types{$response_code} = 1 }
    else { $types{$response_code}++ }
  }
}

printf "Hit:    %d\t%.2f%%\n", $hit_count, ($hit_count/$count*100);
printf "Missed: %d\t%.2f%%\n", $miss_count, ($miss_count/$count*100);
printf "Other:  %d\t%.2f%%\t(%d total)\n", ($count - $hit_count - $miss_count), ((1 - ($hit_count+$miss_count)/$count)*100), $count;

if ($verbose)
{
  print "\n";
  foreach my $key (keys %types)
  {
    printf "%16s: %d\t%.2f%%\n", $key, $types{$key}, $types{$key}/$count*100;
  }
}

