#!/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;
    my $cmd = shift;
    my $user = shift;
    my $saddr = $addr;
    $saddr =~  s/\:.*$//;
    if ($saddr =~ /^[\d\.]+$/)
    {
        $saddr = &get_hostname($saddr);
    }
    my $wsdl = 'https://'.$saddr.'/wsdl/elchemea.wsdl';
    my $soap = SOAP::Lite->on_fault(\&soapGetBad)->service($wsdl);
    if ($cmd)
    {
	print $soap->$cmd($user,@ARGV),"\n";
    }
    else
    {
	print $soap->$user(),"\n";
    }
    exit 0;
};
if ($@)
{
    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 IP or 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);
    print SOCK join(' ',@_),"\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 command [user] [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;
}


sub get_hostname($)
{
    my $ip = shift;
    ### Ugly Ugly Ugly hack for FUBAR DNS setup at DTU   ###                     
    ### where machines get a *.win.dtu.dk dns record in  ###
    ### addition to the requested one!! *ARGH*           ###
    if ($ip && $ip =~ /([\d\.]+)/)
    {
        my @res = `/bin/host $1`;
        foreach my $host (@res)
        {
            next if ($host =~ /win\.dtu\.dk/);
            if ($host =~ /([\-\w\.]+)[\s\t]*$/)
            {
                return $1;
            }
        }

    }
    return $ip;
}

