#!/usr/local/bin/perl -w -- -*- coding: utf-8 -*-

use IO::Socket::INET;
use Net::hostent;
use FileHandle;
use Expect;

use POSIX ":sys_wait_h";
if (scalar(@ARGV) == 1 and $ARGV[0] =~ m/^\d+$/) {
    $serverport = $ARGV[0];
} else {
    $serverport = 3130;
    #$serverport = 3126;
}

sub initMorph {
}

$Expect::Log_Stdout = 0;
$Expect::Multiline_Matching = 0;


$| = 1;


$server = IO::Socket::INET->new(LocalPort => $serverport,
				Type => SOCK_STREAM,
				Reuse => 1,
				Listen => 12)
    or die "Couldn't be a tcp server on port $serverport: $!\n";

print "Starting Generation morphology server on port $serverport\n\n"; #"; $cachecount words cached\n\n";

#$SIG{CHLD} = 'IGNORE';
$SIG{CHLD} = sub { wait };

#$morphinited = 0;

while ($client = $server->accept()) {
    if ($kidpid = fork) {
	close $client;
	next;
    }

    defined($kidpid) or die "cannot fork: $!";

    close $server;
    
    $hostinfo = gethostbyaddr($client->peeraddr);
    printf "[Connect from %s]\n", $hostinfo->name || $client->peerhost;
    if ($hostinfo->name !~ m/cmu.edu$/i && $hostinfo->name !~ m/^localhost$/i) {
	print $client "[Not from CMU.  Closing out connection]\n\n";
	print "[Not from CMU.  Closing out connection]\n\n";
	close($client);
	exit;
    }


    while ($fs = <$client>) {
	if ($fs eq "**EXIT**") {
	    last;
	}

	print $client "$fs\n";



    }
    print "\n[Closing out connection]\n\n";
    close($client);
    exit;
}

close($server);
