#!/usr/bin/perl

use HTTP::Request::Common qw(GET);
use HTTP::Response;
use LWP::UserAgent;
use URI::URL;

$url = $ENV{'QUERY_STRING'};
$url1 = new URI::URL "$url";
$host = $url1->scheme . "://" . $url1->host . "/";

$ua = LWP::UserAgent->new();
$ua->agent( "Mozilla/4.0" );

# mstarnes 3/26/2010: pick random local address
use IO::Interface qw(:flags);
my $s = IO::Socket::INET->new(Proto => 'tcp');
my @interfaces = $s->if_list;
my @ips;
for my $if (@interfaces) {
  push( @ips, $s->if_addr($if) ) if( $s->if_addr($if) && $s->if_addr($if));
}

# pick one
my $ip_index = rand( scalar @ips );
$local_addr = $ips[$ip_index];

$ua->local_address( $local_addr );

$req = HTTP::Request->new( GET => $url );

$response = $ua->request( $req );

print "Content-type: text/html\n\n";

if( $response->is_error() ) {
  $error = $response->error_as_HTML();
  print "<!-- error \n";
  print "$error\n";
  print "-->\n";
} else {
  print "<!-- start -->\n";
  $content = $ua->request($req)->content;
#  $content =~ s/\<head\>/\<head\>\n\<base href=\"$host\"\>/i;
#  #$content =~ s/\<link href=\"\//\<link href=\"$host/i;
#  $content =~ s/\<form action=\"\//\<form action=\"$host/i;
#  $str = "src=\"" . $host . "files/flash/quotes.swf";
#  $content =~ s/src=\"files\/flash\/quotes\.swf/$str/gi;
  print $content;
#  print "<!-- end -->\n";
}

exit(0);
