#!/local/bin/perl

use Getopt::Std;

my %opts;
getopts('h:p:', \%opts);

my $host   = ($opts{h} ? $opts{h} : 'localhost'); 
my $port   = ($opts{p} ? $opts{p} : '10008');

($file) = @ARGV;

$verbose = 0;

if ($file) {
    open (IN, $file) || die "Cannot open $file: $!";
    select IN;
}


$AF_INET = 2;
$SOCK_STREAM = 1;

$SIG{'INT'} = 'dokill';
sub dokill {
    kill 9,$child if $child;
}

$sockaddr = 'S n a4 x8';
$sockaddr = 'S n C4 x8';

chop($hostname = `hostname`);

($name,$aliases,$proto) = getprotobyname('tcp');
($name,$aliases,$port) = getservbyname($port,'tcp')
    unless $port =~ /^\d+$/;;
($name,$aliases,$type,$len,$thisaddr) =
	gethostbyname($hostname);
($name,$aliases,$type,$len,$thataddr) = gethostbyname($them);

$this = pack($sockaddr, $AF_INET, 0, $thisaddr);
$that = pack($sockaddr, $AF_INET, $port, $thataddr);

# Make the socket filehandle.

if (socket(S, $AF_INET, $SOCK_STREAM, $proto)) { 
    printf STDERR "socket ok\n" if $verbose;
}
else {
    die $!;
}

# Give the socket an address.

if (bind(S, $this)) {
    printf STDERR "bind ok\n" if $verbose;
}
else {
    die $!;
}

# Call up the server.

if (connect(S,$that)) {
    printf STDERR "connect ok\n" if $verbose;
}
else {
    die $!;
}

# Set socket to be command buffered.

select(S); $| = 1; select(STDOUT);

# Avoid deadlock by forking.

if($child = fork) {

    while (<>) {
	$buf .= $_;
	$filelength += length;
    }
    print S "G";
    print S pack("n", ($filelength));
    print S $buf;

    do dokill();
}
else {
    while(<S>) {
	print;
    }
}
