#!/usr/bin/perl -w

use strict;

my $VERSION = "1.0";

my $HOOK_EXECUTED_TOKEN = "__POST-PROCESSOR__";

# open the file and convert its contents to a string.
my $file = $ARGV[0];
open FILE, $file or die "Can't open $file for reading\n";
my @text = <FILE>;
close FILE;
my $text = join("", @text);

# check to see if this file has already been processed.  If so, exit.
if ($text =~ /$HOOK_EXECUTED_TOKEN/) {
  print "$file has already been processed.  Ignoring.\n";
  exit(0);
}

# make a timestamp
my @thetime = localtime(time());
my $timestamp  = (1900 + $thetime[5]) . "-" . ($thetime[4] + 1) . "-" . $thetime[3] . " " . $thetime[2] . ":" . $thetime[1] . ":" . $thetime[0];

# extract the page title
$text =~ /<title>(.*)?<\/title>/ims;
my $title = $1;
if ($title ) {
  $title =~ s/\s+/ /g;
} else {
  print "$file has no title.";
}

my $title_declaration = "<!--#set var=\"TITLE\" value=\"$title\"-->";
my $header_include = "<!--#include virtual=\"/header.html\"-->";
my $footer_include = "<!--#include virtual=\"/footer.html\"-->";
my $hook_executed_comment = "<!--THIS FILE AUTO-GENERATED BY $HOOK_EXECUTED_TOKEN v$VERSION at $timestamp-->";

#replace the header and footer with apache virtual includes
$text =~ s|.*<\!--\s*?__START_BODY__\s*?-->|$title_declaration\n$header_include\n$hook_executed_comment\n<!--__START_BODY__-->|ms;
$text =~ s|<\!--__END_BODY__-->.*|<\!--__END_BODY__-->$footer_include|ms;

my $tmpfile = $file . ".tmp" . $$;
open OUTFILE, ">$tmpfile" or die "Can't open $tmpfile for writing\n";
print OUTFILE $text;
close OUTFILE;

my $cmd = "mv $tmpfile $file";
system($cmd) == 0 or die "Failed to replace $file with $tmpfile with the command: $cmd\n";
