#!/usr/bin/perl                                       

use strict;
use warnings;

use SOAP::Lite;
use Data::Dumper; $Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1;
use HTTP::Cookies;

use Term::ReadLine;

@ARGV or die "Usage: $0 proxy [uri [commands...]]\n";
my ($proxy, $uri) = (shift, shift);
my %can;

my $soap = SOAP::Lite->proxy(
        $proxy,
        cookie_jar => HTTP::Cookies->new(
                file => "/tmp/cookies.txt",
                autosave => 1,
                ignore_discard => 1
        )

)->on_fault(sub{});

$soap->uri($uri) if $uri;

my $term = new Term::ReadLine '> ';
my $prompt = '> ';

print STDERR "Usage: method[(parameters)]\n";

while ( defined ($_ = $term->readline($prompt)) ) {
        exit if ($_ eq "quit");
        exit if ($_ eq "exit");
        next unless /\w/;
        my ($method) = /\s*(\w+)/;
        $can{$method} = $soap->can($method) unless exists $can{$method};
        my $res = eval "\$soap->$_";
        $@                               ? print(STDERR join "\n", "--- SYNTAX ERROR ---", $@, '') :
        $can{$method} && !UNIVERSAL::isa($res => 'SOAP::SOM')
                                         ? print(STDERR join "\n", "--- METHOD RESULT ---", $res || '', '') :
        defined($res) && $res->fault     ? print(STDERR join "\n", "--- SOAP FAULT ---", Dumper($res->fault), $res->faultcode, $res->faultstring, '') :
        !$soap->transport->is_success    ? print(STDERR join "\n", "--- TRANSPORT ERROR ---", $soap->transport->status, '') :
                                           print(STDERR join "\n", "--- SOAP RESULT ---", Dumper($res->paramsall), '');

        $term->addhistory($_) if /\S/;
}

