#!/usr/bin/perl -w
#
# Used by t-t2u-start-t2u-oracled
#
# When we appear to be running `ssh <manager> nc.openbsd <socket>`,
# simply cat to/and from the pipes, instead.
#
# So there *is* no AF_UNIX socket in this setup.

use strict;
use POSIX;
use IO::Handle;

if ("@ARGV" !~ /t2u-service-manager-host.*not-really-the-manager-socket/) {
    exec "$ENV{DGIT_TEST_TROOT}/ssh", @ARGV or die $!;
}

print STDERR "$$ ssh-t2u-manager faking: @ARGV\n" or die $!;

my $ocat = fork // die $!;
if (!$ocat) {
    open STDIN, "<&5" or die $!;
    POSIX::close 5 or die $!;
    POSIX::close 6 or die $!;
    exec "cat" or die $!;
}
#print STDERR "$$ OCAT $ocat\n";

my $icat = fork // die $!;
if (!$icat) {
    open STDOUT, ">&6" or die $!;
    POSIX::close 5 or die $!;
    POSIX::close 6 or die $!;

    print "ORACLED-MAKES-FRESH-CONNECTION\n" or die $!;
    STDOUT->flush or die $!;

    exec "cat" or die $!;
}
#print STDERR "$$ ICAT $icat\n";

# Give EOF or EPIPE as appropriate
open STDIN, "</dev/null" or die $!;
open STDOUT, ">&2" or die $!;

my %pids = map { $_, 1 } $icat, $ocat;

my $pid = wait;
#print STDERR "$$ DIED $pid $?\n";

die unless $pids{$pid};
delete $pids{$pid};

foreach my $pid (keys %pids) {
    if ((waitpid $pid, WNOHANG) > 0) {
	#print STDERR "$$ ALSO $pid $?\n";
    } else {
	#print STDERR "$$ KILL $pid\n";
	kill 15, $pid or warn $!;
    }
}

#print STDERR "$$ EXIT\n";
