#!/usr/bin/perl -w

BEGIN {
  use strict;
  use IO::File;
}

$| = 1;

my $LOG          = "/tmp/test_helper.log";

my $arg          = shift || "";
my $read_stdin   = 0;
my $print_stdout = 0;
my $print_stderr = 0;
my $log          = "";


while ( $arg )
{
  if ( $arg eq '-i' )
  {
    $read_stdin = 1;
  }
  elsif ( $arg eq '-o' )
  {
    $print_stdout = 1;
  }
  elsif ( $arg eq '-e' )
  {
    $print_stderr = 1;
  }
  elsif ( $arg eq '-l' )
  {
    $log = shift || $LOG;
  }

  $arg = shift || "";
}

my $logger = new IO::File ();

sub logger ($)
{
  if ( $log )
  {
    $logger->print (shift);
    $logger->flush ();
  }
}



if ( $log )
{
  $logger->open (">>$log") or die "Cannot open log: $!\n";

  logger ("================================\n");
  logger (`date`);
}



if ( $read_stdin )
{

  INPUT:
  while ( <> )
  {
    my $line = $_;


    logger ("stdin: $line");

    if ( $print_stdout )
    {
      print STDOUT "$line";
      logger ("stdout: $line");
    }

    if ( $print_stderr )
    {
      print STDERR "$line";
      logger ("stderr: $line");
    }

    if ( $line =~ /^\s*<exit>\s*$/io )
    {
      last INPUT;
    }
  }
}
else
{
  logger ("non-interactive run\n");

  if ( $print_stdout )
  {
    print STDOUT "stdout test\n";
    logger ("stdout: stdout test\n");
  }

  if ( $print_stderr )
  {
    print STDERR "stderr test\n";
    logger ("stderr: stderr test\n");
  }
}

logger ("================================\n");
