#!/usr/bin/perl -w
use strict;
use Socket;
my ($remote,$port, $iaddr, $paddr, $proto, $line);

if (scalar(@ARGV) < 2)
{
    &help;
    exit;
}
my $adr = shift(@ARGV); 
$adr =~ /(\d+\.\d+\.\d+\.\d+):(\d+)/;
$remote  = $1;
$port    =  $2;
die "No port given!\n" unless ((defined($remote))&&(defined($port)));


if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
     die "No port" unless $port;
     $iaddr   = inet_aton($remote)               || die "no host: $remote";
     $paddr   = sockaddr_in($port, $iaddr);

     $proto   = getprotobyname('tcp');
     socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
     connect(SOCK, $paddr)    || die "connect: $!";
select(SOCK);$|=1;select(STDOUT);
for (my $x = 0; $x < scalar(@ARGV);$x++)
{
    print SOCK "$ARGV[$x] ";
}
print SOCK "\n\n";
my $out = '';
while (defined($line = <SOCK>)) 
{
    $out = $out.$line;
}
my $result = 1;
close (SOCK)            || die "close: $!";
if ($out =~ /command executed/i)
{
    $result = 0;
}
else
{
    print $out,"\n";
}
exit $result;

sub help
{
    print "\n      Remote client for Elchem\n";
    print "\nUsage:  remote-client IPaddress:port [user] [command]\n\n";
    print "Allowed commands is 'impedance' 'potsweep' 'chrono'\n";
    print "The command is run with the current configuration file fur the user\n";
    print "[user] and on the Elchem system will appear as a measurement started\n";
    print "normally except that in the log file the originating IP address of\n";
    print "the command will be logged.\n";
    print "Refer to the EFA.conf file on teh elchem system to find the correct\n";
    print "Port to connect to. Similarly, use ifconfig to find the IP address of\n";
    print "the Elchem system.\n\n";
}
