#!/usr/local/bin/perl
#
# This is a sample program to demonstrate the uses of the --S option
# of Wafe which allows various types of socket communications. This
# perl script functions as application program that calls wafe as a
# subprocess and communicates via sockets with it.
#
# Gustaf Neumann             Mohegan Lake, May 30, 1996

require 'getopts.pl';
if (!&Getopts('umh:')) {
    die "Usage: $0 [options]\n"
	."-u ... use unix domain socket\n"
	."-h ... hostname\n"
	."-m ... use Motif version of Wafe (mofe)\n";
}

if ($opt_m) {
    $Wafe = "mofe";
    $cmd = "XmPushButton b topLevel activateCallback {echo hu};realize\n";
} else {
    $Wafe = "wafe";
    $cmd = "Command c topLevel callback {echo hu};realize\n";
}

if ($opt_u) {
    $unix_domain_socket = "/tmp/wafe$$";
    $wafeArg = "--S$unix_domain_socket";
} else {
    $port = 8853;
    chop($hostname = `hostname`);
    if ($opt_h) {
	$wafeArg = "--S$opt_h:$port";
    } else {
	$wafeArg = "--S$port";
    }
}

$wafeArg .=  " --Dd,socket";
print STDERR "$Wafe $wafeArg &\n";
system("$Wafe $wafeArg &") unless $opt_h;

if ($opt_u) {
    $AF = 1; # AF_UNIX;
    $SOCK = pack('S a*', $AF, $unix_domain_socket);
} else {
    $AF = 2; # AF_INET; 
    ($name, $aliases, $type, $len, $myaddr) = gethostbyname($hostname);
    if ($opt_h) {
	($name, $aliases, $type, $len, $heraddr) = gethostbyname($opt_h);
	$SOCK0 = pack('S n a4 x8', $AF, $port, $myaddr);
	socket(S0,$AF, 1,0) || die "socket $!";
	bind(S0,$SOCK0);
	listen(S0,1);
                 print "listening ...\n";
	system("$Wafe $wafeArg &");
	$addr = accept(NS,S0);

	$newPort = <NS>;
                 print "newPort = $newPort\n";
	close(NS);
#	shutdown(S0,2),
	close(S0);
	$SOCK = pack('S n a4 x8', $AF, $newPort, $heraddr);
    } else {
	$SOCK = pack('S n a4 x8', $AF, $port, $myaddr);
    }
}

socket(S,$AF, 1,0) || die "socket $!";
# wait until wafe is ready...
foreach  (1 .. 100) {
    select(undef,undef,undef, 0.1);
    if ($connected=connect(S,$SOCK)) {
	print STDERR "Connection established\n";
	last;
    }
    print STDERR ".";
}
die "Cannot connect; max number of retries exhausted\n" unless $connected;

# make socket line buffered
select(S); $| = 1;
select(STDOUT);

print S "puts stderr stderr\n";
print S $cmd;
$_=<S>;
print "program said: $_";

