#! /usr/bin/perl -w

use strict;
use File::stat;
use File::Find;
use Data::Dumper;
use POSIX qw(strftime);
use Time::Local;

my $blosxom_data = "/home/sjh/diary/copy_data";
my $blosxom_extension = "text";

my $debug = 0;

# the regex pattern used to recognise a time stamp in a file
# defaults to html comment with time stamp in it such as
# <!-- 2004-10-27 12:01:12 --> capturing it to $1
my $tspattern = '<\!--\s(\d\d\d\d)-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)\s-->';

# format for time output to be passed to strftime, should match $tspattern
my $tsoutfmt = "<!-- %F %T -->";

sub add_datestamp ($$) {
   my ($filename,$mtime) = @_;

   my $timestring = strftime $tsoutfmt, localtime $mtime;

   print STDERR "adding timestamp to $filename\n" if $debug;

   if (open ENTRY, "<$filename") {
      my @filecon = <ENTRY>;
      close ENTRY;
      if (open ENTRY, ">$filename") {
         print ENTRY $filecon[0];
         print ENTRY $timestring, "\n";
         print ENTRY join '', @filecon[1 .. $#filecon];
         close ENTRY;

         # change the atime and mtime of the file back to what it was
         # commented out for now as it does not work unless you are the owner of the file, even if a+w
         print STDERR "utime $mtime on $filename failed $!\n" if not utime $mtime, $mtime, $filename;
      } else {
         warn "couldn't > $filename $!\n";
      }
   }
}

sub extract_date ($) {
   my $filename = shift;

   my $mtime = "";

   if (open ENTRY, "<$filename") {
      my $contents = join '', <ENTRY>;
      close ENTRY;
      # multi line match, looking for an occurance of the timestamp pattern
      if ($contents =~ m/$tspattern/m) {
         my ($y,$m,$d,$h,$mi,$s) = ($1,$2,$3,$4,$5,$6);
         $m--;
         $mtime = timelocal ($s,$mi,$h,$d,$m,$y);
      }
   }

   return $mtime;
}

sub wanted {
   if ($File::Find::name =~ m!^$blosxom_data/(?:(.*)/)?(.+)\.$blosxom_extension$!) {
      # $1 is path (optional) $2 is filename without extension
      # file is not index.something, isnt hidden and is readable
      return if not ($2 ne 'index' and $2 !~ /^\./ and (-r $File::Find::name));

      my $ftime = extract_date ($File::Find::name);
      my $stattime = stat($File::Find::name)->mtime;

      # adds a timestamp to the second line of the entry file needed
      add_datestamp ($File::Find::name, $stattime) if $ftime eq "";
	}
}

find (\&wanted, $blosxom_data);
