#!/usr/local/bin/perl

sub dokill {
    kill 9,$child if $child;
}

sub Opengopher {

    local($them,$port) = @_;	
    $them = 'localhost' unless $them;

    $AF_INET = 2;
    $SOCK_STREAM = 1;

    $SIG{'INT'} = 'dokill';

    $sockaddr = 'S n a4 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.
    socket(S, $AF_INET, $SOCK_STREAM, $proto) || die $!;

    # Give the socket an address.
    bind(S, $this) || die $!;

    # Call up the server.
    connect(S,$that) || die $!;

    # Set socket to be command buffered.
    select(S); $| = 1; select(STDOUT);

}

$DirName = shift(@ARGV) || die "Usage: $0 directory name";

print "Trying $DirName ....\n";
open(GopherFile, "/tmp/.gopher") || die "You haven't run gsetup yet!";
$Firstline = <GopherFile>;
($CurrentHost, $Port, $Path) = split('\t',$Firstline);
close GopherFile;

&Opengopher( $CurrentHost, $Port);

print S "$Path\n";

$NewHost = "moo";

while (<S>) {
    chop;
    chop;
    ($ObjName, $Path, $Host, $Port) = split('\t', $_, 6);
    $Name = substr($ObjName, 1);
    $Obj  = substr($ObjName, 0, 1);
    
    if (($Obj eq "1") && ($Name eq $DirName)) {
	$NewPath = $Path;
	$NewHost = $Host;
	$NewPort = $Port;
    }

}

if ($NewHost eq "moo") {
    print "No such directory\n";
    exit;
}

open(GopherFile, ">/tmp/.gopher");
$Out = sprintf("%s\t%s\t%s", $NewHost, $NewPort, $NewPath);
#$Out = join('\t', $NewHost, $NewPort, $NewPath);
print GopherFile $Out;

close GopherFile;
