#!/usr/bin/perl -w
use strict;
use Socket;
use SOAP::Lite;
our @SOAP_ERRORS = ();

if (scalar(@ARGV) < 2)
{
    &help;
    exit;
}

my @args = @ARGV;

eval {
    my $addr = shift;
    $addr =~  s/\:.*$//;
    my $wsdl = 'https://'.$addr.'/wsdl/elchemea.wsdl';
    my $soap = SOAP::Lite->on_fault(\&soapGetBad)->service($wsdl);
    my $user = shift;
    my $cmd = shift;
    if ($cmd)
    {
	print $soap->$cmd($user,@ARGV);
    }
    else
    {
	print $soap->$user();
    }
    return 0;
};
if ($@)
{
    return remote_client(@args);
}



sub remote_client
{
    my ($remote,$port, $iaddr, $paddr, $proto, $line);
    
    my $adr = shift(@_); 
    $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);
    foreach (@_)
    {
	print SOCK "$_ ";
    }
    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";
    }
    return $result;
}

sub help
{
    print "\n      Remote client for ElchemeaAquisition\n";
    print "\nUsage:  remote-client IPaddress:port [user] [command] [args]\n\n";
    print "For Elchemea systems using webservice access, the port info can be omitted!\n";
    print "Allowed commands is 'impedance' 'potsweep' 'chrono' 'get_file' 'get_file_now'\n";
    print "'ping' 'mode' 'change_channel' and 'session'\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";
}

sub soapGetBad {
    my $soap = shift;
    my $res = shift;
    if( ref( $res ) ) {
        chomp( my $err = $res->faultstring );
        push( @SOAP_ERRORS, "SOAP FAULT: $err" );
    }
    else {
        chomp( my $err = $soap->transport->status );
        push( @SOAP_ERRORS, "TRANSPORT ERROR: $err" );
    }
    warn join(@SOAP_ERRORS),"\n";
    return new SOAP::SOM;
}
