#!/usr/pkg/bin/perl -w
# List backends in the @backends list.
# When ready to accept input, each backend _must_ write one
# newline-terminated line of output to it's stdout. This
# line is then discarded and the next backend is run.

use IO::Handle;
$SIG{PIPE} = 'IGNORE';

my @backends = qw(./cat.pl ./irc.pl);
print("IM script started\n");
$name = $ARGV[0] || "<unnamed>";
for (@backends) {
	pipe(my $read, my $write);
	if (!fork()) {
		open(STDOUT, '>&', $write) or die("open: $!");
		open(STDIN, '>&', $read) or die("open: $!");
		exec($_) or die("exec($_): $!");
	} else {
		chomp(my $in = <$read>);
		close($read);
		print "$_ started\n";
	}
	$_ = [$_, $write];
}
print "Started logging game \"$name\"\n" or die "print()";

while (<STDIN>) {
	chomp;
	print "> $_\n";
	for my $p (@backends) {
		my ($name, $des) = @$p;
		if ($des) {
			if (!(print $des "$_\n")) {
				print("$name died\n");
				$p->[1] = undef;
			}
			$des->flush;
		}
	}
}
