#!/usr/bin/perl -w
use Socket;
($server, $user, $password) = @ARGV;
if (( not defined( $server )) || (not defined( $user )) || (not defined( $password )) ) {
    print "USAGE: jmessaeg.pl <server> <user> <pass>\n";
    exit 0;
}
#connect to the server:
$iaddr = inet_aton($server) or die "no host: $server";
$paddr = sockaddr_in( 5222, $iaddr );

$proto = getprotobyname('tcp');
socket( SOCK, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
connect( SOCK, $paddr );
$sendit =  "<stream:stream to=\"$server\" xmlns:stream=\"http://etherx.jabber.org/streams\" xmlns=\"jabber:client\">\r\n";
send SOCK, $sendit, 0;
while( recv SOCK, $line, 10000, MSG_PEEK) {
    if( ($line =~ /<stream:stream.+>/m) ) {
        #opening line, kill it off the stream
        recv SOCK, $line, 10000, 0;
        #perform login
        my $sendit = "<iq id='PerlLogon' type=\"set\"><query xmlns=\"jabber:iq:auth\"><username>$user</username><password>$password</password><resource>PerlScript</resource></query></iq>\r\n";
        send SOCK, $sendit, 0;
    } elsif ( ($line =~ /<iq.*id=.PerlLogon.* type=.result./ ) ) {
        #our auth was accepted, send a message
        print "TO: ";
        chop( $to = <STDIN> );
        print "Body:";
        chop( $body = <STDIN> );
        recv SOCK, $line, 10000, 0;
        #ask for agents
        my $sendit = "<message to='$to'><body>$body</body></message>\r\n";
        send SOCK, $sendit ,0;
        #message sent, logoff
        print "Message Sent\n";
        exit;
    } elsif ( ($line =~ /error.+<error.*?>(.+)<\/error>/m) ) {
        #some sort of error
        die "error from the server: $1\n";
    } else {
        die "unhandled XML: $line\n";
    }
}
close( SOCK ) or die "close: $!";
exit;