#!/usr/bin/env perl -w

# This simple script uses growlnotify (included in the Growl package) to send
# notifications when your name is highlighted or you get a private message
#
use strict;
use Irssi;
use Irssi::Irc;
use vars qw($VERSION %IRSSI);

$VERSION = '0.1';
%IRSSI = (
    authors     => "Sebastian Wehrmann",
    contact     => 'kontakt@sw83.de',
    name        => 'sw.growlnotify',
    description => 'This script enables growl notifications for irssi.',
    url         => 'https://bitbucket.org/sweh/sw.growlnotify.pl',
    license     => 'BSD',
    changed     => "2011-04-15"
);

# settings
Irssi::settings_add_str($IRSSI{'name'}, 'gn_growlnotify_path', '/usr/local/bin');
Irssi::settings_add_str($IRSSI{'name'}, 'gn_remote_host', '');
Irssi::settings_add_str($IRSSI{'name'}, 'gn_remote_pass', '');
Irssi::settings_add_str($IRSSI{'name'}, 'gn_icon_path', '');
Irssi::settings_add_bool($IRSSI{'name'}, 'gn_debug', 0);

sub growl_text_public ($$$) {
  my ($dest, $text, $stripped) = @_;

  if (($dest->{level} & (MSGLEVEL_HILIGHT|MSGLEVEL_MSGS)) && (($dest->{level} & MSGLEVEL_NOHILIGHT) == 0) && ($dest->{level} & MSGLEVEL_PUBLIC)) {
    growl($dest->{target}, $stripped);
  }
}

sub growl_text_private ($$$$) {
  my ($server, $msg, $nick, $address) = @_;

  growl($nick, $msg);
}

sub growl ($$) {
    my ($channel, $message) = @_;
    my $channel = "\\" . $channel;
    my $path = Irssi::settings_get_str('gn_growlnotify_path');
    my $host = Irssi::settings_get_str('gn_remote_host');
    my $pass = Irssi::settings_get_str('gn_remote_pass');
    my $icon = Irssi::settings_get_str('gn_icon_path');
    my $debug = Irssi::settings_get_bool('gn_debug');

    if ($host) { $host = "-H " . $host; }
    if ($pass) { $pass = "-P " . $pass; }
    if ($icon) { $icon = "--image " . $icon; }

    if ($debug) {
        print $path.'/growlnotify '.$host.' '.$pass.' '.$icon.' -n "Irssi" -m "'.$message.'" '.$channel;
    }
    `$path/growlnotify $host $pass $icon -n "Irssi" -m "$message" $channel`;
}

sub gn_help {
    Irssi::print('sw.growlnotify.pl can be configured with these settings:');

    Irssi::print('%ygn_growlnotify_path%n: Path to the growlnotify executable.');
    Irssi::print('%ygn_remote_host%n: A hostname to which to send a remote notification.');
    Irssi::print('%ygn_remote_pass%n: Password used for remote notifications.');
    Irssi::print('%ygn_icon_path%n : Specify a file whose icon will be the notification icon.');
    Irssi::print('%ygn_debug%n : Print out the command used to send the notifications.');
}

sub gn_test {
    growl("sw.growlnotify test", 'Testmessage');
}

Irssi::command_bind('gn-help', 'gn_help');
Irssi::command_bind('gn-test', 'gn_test');
Irssi::signal_add('print text', 'growl_text_public');
Irssi::signal_add('message private', 'growl_text_private');

Irssi::print('%G>>%n '.$IRSSI{name}.' '.$VERSION.' loaded (/gn-help for help, /gn-test for test.)');
