#!/usr/bin/perl -w

use strict;

use Net::XMPP;
use Carp;

our $verbose = 0;

our $session = time;

my $host = shift;
my $username = shift;
my $password = shift;
my $ponger = shift;

my $client = new Net::XMPP::Client();

$client->SetCallBacks(message => \&message);

$client->Connect(hostname => $host);

my @result = $client->AuthSend(username => $username,
			       password => $password,
			       resource => 'Ping');

print join(', ', @result), "\n";

croak $result[0] if $result[0] ne 'ok';

print "Connected\n";

$client->PresenceSend();

print "Sent presence\n";

my $prev = 0;
my $count = 0;
our $got;
while(defined(my $status = $client->Process(1))) {
    print "Processing ($status)\n" if $verbose;
    # continue if not ping time
    next if $prev+10 > time;
    $prev = time;

    my $msg = new Net::XMPP::Message();
    $msg->SetMessage(to => "$ponger",
		     body => "Ping $session/$count!");
    $client->Send($msg);
    print "Ping $session/$count to $ponger\n";
    ++$count;
}

print "ERROR: The connection was killed...\n";

sub message
{
    my $sid = shift;
    my $message = shift;

    my $type = $message->GetType();
    my $fromJID = $message->GetFrom("jid");
    my $from = $fromJID->GetUserID();
    my $resource = $fromJID->GetResource();
    my $subject = $message->GetSubject();
    my $body = $message->GetBody();

    if ($verbose) {
	print "===\n";
	print "Message ($type)\n";
	print "  From: $from ($resource)\n";
	print "  Subject: $subject\n";
	print "  Body: $body\n";
	print "===\n";
	print $message->GetXML(),"\n";
	print "===\n";
    }

    if ($body =~ /^Pong (\d+)\/(\d+)!$/) {
	my($pongsess, $seq) = ($1, $2);
	if ($pongsess != $session) {
	    print '---';
	} else {
	    ++$got;
	}
	print "Got pong $pongsess/$seq from ", $message->GetFrom(),
	  ", $got of $count\n";
    }
}
