#! /usr/bin/perl
# Copyright (C) 2006  Alex Schroeder <alex@emacswiki.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

my $PageDir = 'page';
my $Now = time;

sub ParseData {
  my $data = shift;
  my %result;
  while ($data =~ /(\S+?): (.*?)(?=\n[^ \t]|\Z)/sg) {
    my ($key, $value) = ($1, $2);
    $value =~ s/\n\t/\n/g;
    $result{$key} = $value;
  }
  return %result;
}

local $/ = undef;   # Read complete files

my %Month = ();
my %Age = ();
my %Hits = ();

# include dotfiles!
foreach my $file (glob("$PageDir/*/*.pg $PageDir/*/.*.pg")) {
  next unless $file =~ m|/.*/(.+)\.pg$|;
  my $page = $1;
  open(F, $file) or die "Cannot read $page file: $!";
  my $data = <F>;
  close(F);
  my %result = ParseData($data);
  my $days = ($Now - $result{ts}) / (24 * 60 * 60);
  $Month{int($days/100)+1}++;
  $Age{$page} = $days;
};

print "Days\t#Pages\n";
for my $key (reverse(sort { $a <=> $b } (keys %Month))) {
  print $key * 100, "\t", $Month{$key}, "\n";
}
