#!/usr/bin/perl
###########################################
# agent - Jabber agent behind firewall
# Mike Schilli, 2004 (m@perlmeister.com)
###########################################
use warnings;
use strict;

use Net::Jabber qw(Client);
use Log::Log4perl qw(:easy);
use LWP::Simple;

Log::Log4perl->easy_init(
    { level => $DEBUG, 
      file => '>>/tmp/agent.log' });

my $JABBER_USER   = 'mikes-agent-receiver';
my $JABBER_PASSWD = "*****";
my $JABBER_SERVER = "jabber.org";
my $JABBER_PORT   = 5222;

our %ROSTER;

my $c = Net::Jabber::Client->new();

$c->SetCallBacks(

  message => sub {
    my $msg = $_[1];

    my $sender = $msg->GetFrom();

    DEBUG "Message '", $msg->GetBody(), 
          "' from $sender";

        # Remove /GAIM resource
    $sender =~ s#/\w+$##;

    if(! exists 
       $ROSTER{$sender}) {
        INFO "Denied ($sender not in roster ", join('#', keys %ROSTER), ")";
        return;
    }

    DEBUG "Running ", $msg->GetBody();
    my $rep = run_cmd($msg->GetBody());
    chomp $rep;
    DEBUG "Result: ", $rep;

    $c->Send($msg->Reply(body => $rep));
  },

  onauth => sub {
    DEBUG "Auth";
    %ROSTER = $c->RosterGet();
    $c->PresenceSend();
  },

  presence => sub { 
    # Ignore all subscription requests
  },
);

DEBUG "Connecting ...";

$c->Execute(
  hostname => $JABBER_SERVER,
  username => $JABBER_USER,
  password => $JABBER_PASSWD,
  resource => 'Script',
);

$c->Disconnect();

###########################################
sub run_cmd {
###########################################
  my($cmd) = @_;

    # Find out external IP
  if($cmd eq "ip") {
    return LWP::Simple::get(
    "http://perlmeister.com/cgi/whatsmyip"
    );
  }

    # Print Load
  if($cmd eq "load") {
    return `/usr/bin/uptime`;
  }

    # Switch bedroom light on/off
  if($cmd =~ /^lamp\s+(on|off)$/) {
    my $rc = system("/usr/bin/lamp $1");
    return $rc == 0 ? "ok" : 
                      "not ok ($rc)";
  }

  return "Unknown Command";
}
