#!/usr/bin/perl

use LWP::UserAgent;

# if you want to expand pages for other Institue sites, then you need to
# update this

$website = "www.inf.ed.ac.uk";

$file=$ARGV[0];

if (!($file=$ARGV[0])) {
  print "Usage: ssiexpand <file>\n";
  exit 1;
}
rename $file,"$file.bak" or die "Unable to backup $file : $!";
open(READ,"$file.bak") or die "Unable to open $file for reading : $!";
open(WRITE,">$file") or die "Unable to open $file for writing: $!";

while (<READ>) {
  if (/<!--#include virtual=\"(.*)\"-->(.*)/) {
     $ssi=$1; $extra=$2;
     $ua = new LWP::UserAgent;
     $ua->agent("SSIExpand/0.1 " . $ua->agent);

     my $req= new HTTP::Request GET => " http://$website/$1";
     my $res=$ua->request($req);
     
     die "Couldn't fetch $ssi\n" if !($res->is_success);

     # look for local hrefs in the include and expand then to FQ
     $content = $res->content; 
     $content =~ s|(<[^>]*)\shref=\"/|$1 href=\"http://$website/|igs;
     # Do the same for src="/
     $content =~ s|(<[^>]*)\ssrc=\"/|$1 src=\"http://$website/|igs;

     print WRITE $content;
     print WRITE $extra;
  } else { print WRITE $_; }
}

close(READ);
close(WRITE);
