##
## Put me in ~/.irssi/scripts, and then execute the following in irssi:
##
##       /load perl
##       /script load notify
##

use strict;
use Irssi;
use vars qw($VERSION %IRSSI);

$VERSION = "0.01";
%IRSSI = (
    authors     => 'Luke Macken, Paul W. Frields',
    contact     => 'lewk@csh.rit.edu, stickster@gmail.com',
    name        => 'notify.pl',
    description => 'Use libnotify to alert user to hilighted messages',
    license     => 'GNU General Public License',
    url         => 'http://lewk.org/log/code/irssi-notify',
);

Irssi::settings_add_str('notify', 'notify_icon', 'gtk-dialog-info');
Irssi::settings_add_str('notify', 'notify_time', '5000');

sub notify {
    my ($server, $urgency, $summary, $message) = @_;

    # Make the message entity-safe
    $message =~ s/&/&amp;/g; # That could have been done better.
    $message =~ s/</&lt;/g;
    $message =~ s/>/&gt;/g;
    $message =~ s/'/&apos;/g;

    my $cmd = "EXEC - notify-send" .
	" -i " . Irssi::settings_get_str('notify_icon') .
	" -t " . Irssi::settings_get_str('notify_time') .
	" -u '" . $urgency . "'" .
	" -- '" . $summary . "'" .
	" '" . $message . "'";

    $server->command($cmd);
}
 
sub print_text_notify {
    my ($dest, $text, $stripped) = @_;
    my $server = $dest->{server};
    my $urgency = "low";

    return if (!$server || !($dest->{level} & MSGLEVEL_HILIGHT));
    my $sender = $stripped;
    $sender =~ s/^\<.([^\>]+)\>.+/\1/ ;
    $stripped =~ s/^\<.[^\>]+\>.// ;
    my $summary = $dest->{target} . ": " . $sender;
    notify($server, $urgency, $summary, $stripped);
}

sub message_private_notify {
    my ($server, $msg, $nick, $address) = @_;
    my $urgency = "low";
    return if (!$server);
    return if ($nick =~ /micah/);
    notify($server, $urgency, "Private message from ".$nick, $msg);
}

sub dcc_request_notify {
    my ($dcc, $sendaddr) = @_;
    my $server = $dcc->{server};
    my $urgency = "low";

    return if (!$dcc);
    notify($server, $urgency, "DCC ".$dcc->{type}." request", $dcc->{nick});
}

sub notice_message_notify {
    my ($server, $data, $source) = @_;
    my $urgency = "low";

    return if ($data =~ /#emacs/ || $source =~ /(NickServ|OperServ|ChanServ)/);
    $data =~ s/#nagios-status ://;
    if ($data =~ /WARNING/) {
	$urgency = "normal";
    } elsif ($data =~ /CRITICAL/) {
	$urgency = "critical";
    } elsif ($data =~ /OK/) {
	$urgency = "low";
    }
    notify($server, $urgency, $data);
}

Irssi::signal_add('print text', 'print_text_notify');
Irssi::signal_add('message private', 'message_private_notify');
Irssi::signal_add('dcc request', 'dcc_request_notify');
Irssi::signal_add('event notice', 'notice_message_notify');
