#!/usr/bin/perl -w

use locale;
use Data::Dumper;

sub output { my $f = shift; local *F; open F, ">$f" or die "output in file $f failed: $!\n"; print F foreach @_; }
sub cat_ { local *F; open F, $_[0] or return; my @l = <F>; wantarray ? @l : join '', @l }

$conffile = "$ENV{HOME}/.xchat/gcnotice.conf";
eval(cat_($conffile));

sub privmsg_handler_gc {

    my $current_channel = IRC::get_info(6);
    my $channel = IRC::get_info(2);

    my $actLine = shift(@_);
    $actLine =~ m/\:(.*?)\!(.*?)\sPRIVMSG\s(.*?)\s\:(.*)?/;
    my $msgNick = $1;
    my $msgLine = $4;

    my $myNick = IRC::get_info(1);


    $msgNick !~ $regexp and return;

    if ($channel =~ /^#/ ? #- message on a channel
                            ($when eq 'always' || $current_channel ne $channel) && $msgLine =~ /\b$myNick\b/
                          : #- private message
                            ($when eq 'always' || $current_channel ne $msgNick)) {
        system("/usr/bin/esdplay /home/gc/.xchat/typewriter.wav &")
    }
}

sub configure {
    my ($arg1, $arg2) = split /\s/, $_[0];

    my %actions = (
        all => sub {
            IRC::print('gcnotice: reacts to all');
            $who = 'all';
            $regexp = '.';
        },
        ann => sub {
            IRC::print('gcnotice: reacts to Ann');
            $who = 'ann';
            $regexp = "Ann|MacLann";
        },
        regexp => sub {
            IRC::print("gcnotice: reacts to regexp $arg2");
            $who = 'REGEXP';
            $regexp = $arg2;
        },

        always => sub {
            IRC::print('gcnotice: always reacts');
            $when = 'always';
        },
        unnoticed => sub {
            IRC::print('gcnotice: unnoticed reacts');
            $when = 'unnoticed';
        },

        query => sub {
            IRC::print("gcnotice: currently who<$who> when<$when> regexp<$regexp>");
        },
                  );

    $arg1 eq '' and $arg1 = 'query';
    if (exists $actions{$arg1}) {
        $actions{$arg1}->();
        output($conffile, Data::Dumper->Dump([ $who, $when, $regexp ], [ qw(who when regexp) ]));
    } else {
        IRC::print("gcnotice: unrecognized option `$arg1', options are: " . join(', ', keys %actions));
    }
}


IRC::add_message_handler('PRIVMSG', 'privmsg_handler_gc');
IRC::add_command_handler('gcnotice', 'configure');

