#!/afs/athena/contrib/perl5/perl
#require 'sys/socket.ph';
# SunOS constants:

require 'conv-lib2.pl';
&readcharacter("webmaster");
sub AF_INET { 2; }
sub SOCK_STREAM { 1; }
#($port) = @ARGV;
$port = 9005 unless $port;

$|=1;

$sockaddr = 'S n a4 x8';

($name, $aliases, $proto) = getprotobyname('tcp');
if ($port !~ /^\d+$/) {
    ($name, $aliases, $port) = getservbyport($port, 'tcp');
}

print "Port = $port\n";

$this = pack($sockaddr, &AF_INET, $port, "\0\0\0\0");

select(NS); $| = 1; select(stdout);

socket(S, &AF_INET, &SOCK_STREAM, $proto) || die "socket: $!";
bind(S,$this) || die "bind: $!";
listen(S,5) || die "connect: $!";

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

$con = 0;
print "Listening for connection 1....\n";
for(;;) {
    ($addr = accept(NS,S)) || die $!;

    $con++;
    if (($child[$con] = fork()) == 0) {
	print "accept ok\n";
	$STATE = "init";
	($af,$port,$inetaddr) = unpack($sockaddr,$addr);
	@inetaddr = unpack('C4',$inetaddr);
	print "$con: $af $port @inetaddr\n";
	select(NS); $|=1; select(STDOUT);
	while(1){
	    vec($rin, fileno(NS), 1) = 1;
	    if(select($rout = $rin, undef, undef, .03) > 0){
		$d = <NS>;
		if($d eq ""){
		    print "Closing connection\n";
		    exit;
		}
		$d =~ s/[\n\r]//g;
		print "Usersaid $d\n";
		&usersaid($d);
	    }
	    if($#tosay >= 0){
		if($wait < 0){
		    print NS $tosay[0], "\n";
		    if($tosay[0] eq "Connection closed."){
			exit;
		    }
		    shift @tosay;
		    $wait = length($tosay[0]);
		}
		$wait--;
	    }
	}

	while (<NS>) {
	    &usersaid($_);
	}
	close(NS);
	exit;
    }
    close(NS);

    printf("Listening for connection %d\n",$con+1);
}

sub usersaid {
    $t = shift;

    $r = &respond($t);
    @r = split(/\^/, $r);
    if($#tosay < 0){
	$wait = length($r[0]);
    }
    push(@tosay, @r);
}

