#!/opt/gnu/bin/perl
# This script is Copyright 1995, Steven Dick <ssd@mae.engr.ucf.edu>
# Copy this freely, use as you like, but please send me e-mail.

# Show stats sorted by tag;
# Note: This may be inaccurate if more than one URL uses the same tag.

require 'getopt.pl';
&Getopt('trcw');
#  Usage: 
#   showtstats [keys]
#   showtstats [options]
#  options will be ignored if keys are listed
#    -t min time
#    -r min rate
#    -c min total count
#    -w min weekly count

%units = ( 
  's', 1,
  'm', 60,
  'h', 3600,
  'd', 86400,
  'w', 604800,
  'M', 2635200,
  'y', 31557600,
);
if (defined($opt_t) && $opt_t =~ /^(\d+)([hmsMywd])$/){
# handle opt_t as a time with units
  $opt_t = time - $1 * $units{$2};
  print "time: $opt_t ",time," ",time - $opt_t,"\n";
}


# struct counter_stat {
#   long count;                          /* total hits */
#   long weekly;                         /* hits since last reset */
#   long creation, lastaccess,lastreset; /* timestamps */
# };
$DBformat = "lllll";
#$base="/tmp/counter";
$base="/home/system/www/c-";

dbmopen(%keys,"${base}counters",666);

sub age {
  local ($when) = @_;
  $age = time - $when;

  $unit='s';
  if ($age > 31557600 ) {
    $age /= 31557600 ;
    $unit='y';
  } elsif ($age > 2635200 ) {
    $age /= 2635200 ;
    $unit='M';
  } elsif ($age > 86400 ) {
    $age /= 86400 ;
    $unit='d';
  } elsif ($age > 3600 ) {
    $age /= 3600;
    $unit='h';
  } elsif ($age > 60) {
    $age /= 60;
    $unit = 'm';
  }
  sprintf("%.0f%s",$age,$unit);
}

format top = 

total week  age reset   rate key
.
format =
@>>>> @>>> @>>> @>>>> @>>>>> @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
$val, $weekly, &age($creation), &age($lastreset).$new, $rate, $key 
.

sub showdata {
  local ($tag,$pval) = @_;
  local ($val,$weekly,$creation,$lastaccess,$lastreset,$new,$x);

  $new = ' ';
  ($val,$weekly,$creation,$lastaccess,$lastreset) = unpack($DBformat,$pval);
  return if (defined($opt_c) && $val < $opt_c);
  return if (defined($opt_w) && $weekly < $opt_w);
  return if (defined($opt_t) && ($lastreset > $opt_t || $creation>$opt_t));
  if ($lastreset<=$creation){
    $lastreset = $creation ;
    $new = 'N';
  }
  if ($lastreset) {
##   print "\t",$weekly / ((time-$lastreset)/86400),"\n";
    $rate = int($weekly *86400 / ($x=time-$lastreset));
    return if (defined($opt_r) && $rate < $opt_r);
    $rate = '~'.$rate if ($x < 259200);
#    if ($lastreset && $creation!=$lastreset){
#      $rate2 = int($val *86400 / ($x=time-$creation));
#    } else {
#      $rate2="";
#    }
  } else { 
    return if (defined($opt_r));
    $rate = "N/A";
#    print "\n"; 
  }
  write;
}

if (@ARGV){
    foreach $key (@ARGV){ 
      &showdata($key,$keys{$key}) if (defined($keys{$key}));
    }
} else {
  while (($key,$pval) = each %keys) {
    &showdata($key,$pval);
  }
}
dbmclose(%keys);
