package Tak::STDIOSetup;

BEGIN { require MRO::Compat; }

use Tak::ConnectionService;
use Tak::Router;
use Tak;
use strictures 1;

sub run {
  open my $stdin, '<&', \*STDIN;
  open my $stdout, '>&', \*STDOUT;
  # if we don't re-open them then 0 and 1 get re-used - which is not
  # only potentially bloody confusing but results in warnings like:
  # "Filehandle STDOUT reopened as STDIN only for input"
  close STDIN; open STDIN, '<', '/dev/null';
  close STDOUT; open STDOUT, '>', '/dev/null';
  my $done;
  my $connection = Tak::ConnectionService->new(
    read_fh => $stdin, write_fh => $stdout,
    listening_service => Tak::Router->new,
    on_close => sub { $done = 1 }
  );
  $connection->receiver->service->register_weak(remote => $connection);
  if ($0 eq '-') {
    $0 = 'tak-stdio-node';
  }
  Tak->loop_until($done);
}

1;
