#!/usr/bin/perl
use IO::Socket;

# Parse the command line.
my $arg = '';
my $argFileInputName = '';
my $argFileOutputName = '';
my $argIdx = 0;
my $argIdxMax = $#ARGV;
my $argIdxPosn = 0;
my $argOptCount = 0;
my $argServer = '';
my $argPort = 0;
my $argTimeout = 0;
my $errText = '';

while (($argIdx <= $argIdxMax) && ($errText eq '')) {
 $arg = $ARGV[$argIdx];
 if (substr($arg, 0, 1) ne '-') {
  $argIdxPosn = $argIdx - $argOptCount;
  if ($argIdxPosn == 0) { ($argServer, $argPort) = split(/:/, $arg, 2); }
  elsif ($argIdxPosn == 1) { $argFileInputName = $arg; }
  elsif ($argIdxPosn == 2) { $argFileOutputName = $arg; }
  else { $errText = 'Unknown positional parameter: ' . $arg; }
 } else {
  $arg = uc($arg);
  if ($arg eq '-T') {
   if ($argIdx < $argIdxMax) {
    $argIdx++;
    $argOptCount++;
    $argTimeout = $ARGV[$argIdx];
   } else {
    $errText = 'Missing timeout value';
   }
  } else {
   $errText = 'Unknown option: ' . $arg;
  }
  $argOptCount++;
 }

 $argIdx++;
}

if ($errText eq '') {
 if ($argFileOutputName ne '') {
  if (!open(STDOUT, '>' . $argFileOutputName)) {
   $errText = 'Unable to open output file: ' . $argFileOutputName;
  }
 }
}

if (($argServer ne '') && ($argFileInputName ne '') && ($errText eq '')) {
 my $fileInputSize = 0;
 my $tcpClient;

 # Defaults
 if ($argPort eq '') { $argPort = 9278; }
 if ($argTimeout = 0) { $argTimout = 5; } # IO::Socket::INET doesn't support timeout anyway, so ...

 if ($errText eq '') {
  # Get size of input file.
  if (-e $argFileInputName) {
   $fileInputSize = -s $argFileInputName;
  } else {
   $errText = 'Input file not found: ' . $argFileInputName;
  }
 }

 if ($errText eq '') {
  if (!open(INPUTFILE, $argFileInputName)) {
   $errText = 'Unable to open input file: ' . $argFileInputName;
  }
 }

 if ($errText eq '') {
  # Open the socket to the M3Services service.
  $tcpClient = new IO::Socket::INET (
    PeerAddr => $argServer . ':' . $argPort,
    Proto => 'tcp'
   );
  if (!$tcpClient->connected()) {
   $errText = 'Failed to connect to: ' . $argServer . ':' . $argPort;
  }
 }

 if ($errText eq '') {
  # Send header with type and file size.
  print $tcpClient pack 'CLL', 1, $fileInputSize, 0;
  # Send file
  binmode(INPUTFILE);
  while (<INPUTFILE>) { print $tcpClient $_; }
  close(INPUTFILE);

  # Get & output response.
  while ( <$tcpClient> ) { print STDOUT $_; }
  close($tcpClient);
 }
} else {
 if ($errText eq '') {
  $ERRNO = 9001;
  $errText = 'Syntax: M3ServicesCmd <server:port> <input file name> [<output file name>] [-T <timeout secs>]';
 } else {
  $ERRNO = 9000;
 }
}

if ($errText ne '') {
 print STDOUT 'ERROR: ' . $errText, "\n";
}

if (STDOUT) { close(STDOUT); }
exit;