#!/usr/bin/perl -T

use strict;
use warnings;

use LWP::UserAgent;
use CGI;
#  use LWP::Debug qw(+ -conns);

my $sitename = lc($ENV{'SERVER_NAME'});

my ($realurl, $sitenick);
my $basedir = "/home/hatter/slackpete";

if ($sitename =~ /pete/) {
    #my $realurl = "http://www.petesrockets.co.uk";
    $realurl = "http://web.archive.org/web/20041125091932/http://www.petesrockets.co.uk";
    $sitenick = "slack";
}
elsif ($sitename =~ /deeps/) {
    $realurl = "http://www.deepskyrocketshop.co.uk";
    $sitenick = "deepshite";
}
elsif ($sitename =~ /thing/) {
    $realurl = "http://www.rocketsandthings.com";
    $sitenick = "randt";
}

my $q = CGI->new();

my $uri = $q->url(-absolute=>1)||'/';
my $ua = LWP::UserAgent->new(debug=>1);
#LWP::Debug::trace('get()');
my $response = $ua->get("$realurl$uri");


my $h = $$response{'_headers'};
my $ctype = $h->header('Content-type');
my $content = $$response{'_content'};

my ($fname) = ($uri =~ m#/([^/]+)$#);

# Firstly, the complete replacement files option
if (-f "$basedir/files/slack$fname") {
    $content = '';
    open(FILE,"<$basedir/files/slack$fname");
    while (<FILE>) {$content .= $_}
    close FILE;
}
# Or the inline text replacements
elsif ($ctype eq "text/html") {
    # Remove WaybackEngine rewrite code
    $content =~ s/<SCRIPT.+INTERNET ARCHIVE.+<\/SCRIPT>//smi;

    if ($sitenick eq 'slack') {
        $content =~ s/(Pete[ \.\'])/Slack $1/mig;
        $content =~ s/The UK's Premier High Power/The UK's Most Laid Back High Power/mig;
        $content =~ s/(?:www\.)?petesrockets\.co\.uk/slackpetes.rocketry.co.uk/mig;
        $content =~ s/davy\@btinternet.com/slackpete\@rocketry.co.uk/mig;
    }
}

foreach ('Date','Content-type','Last-Modified','ETag','Cookie','Set-Cookie') {
    print "$_: ".$h->header($_)."\n";# if $h->header($_);
}
print "Content-Length: ".length($content)."\n";
print "\n";

#print "Content-type: ".$ctype."\n\n";
#print "Last-Modified: "

print $content;


