use strict;
use Irssi;
use Net::Growl;
use IO::Socket::INET;
use vars qw($VERSION %IRSSI);

$VERSION = "1.00";
%IRSSI = (authors     => "f0rked",
          contact     => "root\@f0rked.com",
          name        => "mumbles",
          description => "Irssi integration with mumbles/growl",
          license     => "Public Domain",
          url         => "http://f0rked.com",
          changed     => "2007-10-08");

# Run the command when away?
my $run_cmd_when_away = 0;
my @hosts = qw/10.64.0.12 10.64.0.32/;
my $password = "YOURGROWLPASSWORD";

sub send_growl
{
  my($host, $title, $text) = @_;
  my %addr = (PeerAddr => $host,
              PeerPort => Net::Growl::GROWL_UDP_PORT,
              Proto    => "udp");
  my $s = IO::Socket::INET->new(%addr) || die "Could not create socket: $!\n";
  my $r = Net::Growl::RegistrationPacket->new(application => "Perl Notifier",
                                              password    => $password);
  $r->addNotification();
  print $s $r->payload();

  # send a notification
  my $p = Net::Growl::NotificationPacket->new(application => "Perl Notifier",
                                              title       => $title,
                                              description => $text,
                                              priority    => 2,
                                              sticky      => 'True',
                                              password    => $password);
  print $s $p->payload();
  close $s;
}

sub event_privmsg
{
  my($server, $msg, $nick, $address, $target) = @_;
  my $active = Irssi::active_win();
  return if $active->get_active_name() eq $nick;
  send_growl($_, "irssi: $nick", "new private message from $nick") for @hosts;
}

sub event_printtext
{
    my ($dest, $text, $stripped) = @_;
    my $server = $dest->{server};

    # Do not run the command if we're not supposed to when away
    if ($server->{usermode_away} && !$run_cmd_when_away) { return; }

    # Run the command if we're hilighted
    if (($dest->{level} & (MSGLEVEL_HILIGHT)) &&
        ($dest->{level} & MSGLEVEL_NOHILIGHT) == 0) {
      send_growl($_, "irssi: hilight", $stripped) for @hosts;
    }
}

Irssi::signal_add("message private", \&event_privmsg);
Irssi::signal_add("print text", \&event_printtext);
