# gaway.pl
# Defines /gaway command. Use /gaway <short name> where <short name> is the
# name defined for a <status> tag in ~/.gaim/status.xml. The script will set
# all connections as away with the message defined in the <message> tag for
# that particular shortname.

use strict;
use Irssi;
use HTML::Entities;
use vars qw($VERSION %IRSSI);
$VERSION="1.0";
%IRSSI = (
    authors     => "Matt 'f0rked' Sparks",
    contact     => "root\@f0rked.com",
    name        => "gaway",
    description => "adds /gaway <short name> command for going away with gaim's away messages",
    license     => "GPLv2",
    url         => "http://f0rked.com",
    changed     => "2005-06-16",
    commands    => "gaway"
);

# Location of the gaim status.xml file
my $file = "$ENV{HOME}/.gaim/status.xml";

sub cmd_gaway {
    my ($short_name)=@_;
    my $msg;
    if ($msg=get_gaim_away_message($short_name)) {
        Irssi::print "Setting away: $msg";
        Irssi::active_win()->command("away $msg");
    } else {
        Irssi::print "Failed to get gaim away message. Not setting away.",MSGLEVEL_CLIENTERROR;
    }
}

sub get_gaim_away_message {
    my ($short_name)=@_;
    
    open(HANDLE,$file) || Irssi::print "Failed to open $file", MSGLEVEL_CLIENTERROR;
    my @data=<HANDLE>;
    close(HANDLE);

    $_=join("",@data);
    
    my %messages=();
    my @matches = /<status name=\"(.*?)\">.*?<state>away<\/state>.*?<message>(.*?)<\/message>.*?<\/status>/sg;
    
    my $i=0;
    foreach (@matches) {
        $messages{super_decode($matches[$i])}=super_decode($matches[$i+1]) if $matches[$i];
        $i+=2;
    }

    return (exists $messages{$short_name}) ? $messages{$short_name} : "";
}

sub super_decode {
    # Decode twice, because some messages are weird.
    my ($text)=@_;
    $text = decode_entities($text) for (1..2);
    return $text;
}

Irssi::command_bind("gaway", \&cmd_gaway);
