#!/opt/default/bin/perl -w

use strict;
use sigtrap;
use Socket;

my $url = $ARGV[0];
$url =~ s%http://%%;
my ($adr, $rest) = split('/', $url, 2);
$rest = '' if (!defined($rest));
	print "adr=[$adr], rest=[$rest]\n";

my ($remote, $port, $iaddr, $paddr, $proto, $line);

$remote = $adr;
$port = 80;  # http
$iaddr = inet_aton($remote)  or die "no host: $remote";
$paddr = sockaddr_in($port, $iaddr);

$proto = getprotobyname('tcp');
socket(SOCK, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
connect(SOCK, $paddr) or die "connect: $!";

my $q = "GET /$rest HTTP/1.0\r\n\r\n";
syswrite SOCK, $q, length($q) || die "syswrite: $!";

# my @lines = <SOCK>;
# print @lines;

while ($line = <SOCK>) {
	check($line) if ($line ne "\n");
}
my @lines = <SOCK>;
print @lines;


close(SOCK)  or die "close: $!";
exit;

sub check() {
	my $moved = 1;
	print "in header $line";
	$moved = 1 if ($line =~ /HTTP.*Moved/);
	$moved = 1 if ($line =~ /HTTP.*Found/);
	if ($moved == 1 && $line =~ /Location: .*/) {
		$line =~ s/Location: //;
print "execing geturl.pl $line";
		exec "geturl.pl $line";
	}
}

