#!/usr/bin/perl -w
#
# Copyright 2005, Karl Y. Pradene <knotty@cpan.org> All rights reserved.
#
# Dumb Bot for test Net::IRC2

use Net::IRC2;

use strict; 
use warnings;
$| = 1;

sub p($) { print "@_\n" }

# Make a new bot
my $bot = new Net::IRC2;
print "New Bot OK\n";

# Make a new connection
my $conn = $bot->newconn( uri => 'irc://B1-66ER!void@194.242.113.162:6667/' )
           or die 'No Connection' ;
print "Conn OK\n";

# Set +B user mode: for the bot on the exemple network
$conn->mode($conn->nick,'+B-x');

# Get the socket associated with a specific connection
# my $sock = $conn->socket;

# All IRC messages from ALL connections will be dump
$bot->add_default_handler(\&dump_event);

# IRC messages with command as number between 002 and 999 will be dump
# $bot->add_handler(['002'..'999'], \&dump_event);

# Ignore messages with command 372
# $bot->add_handler(['372'], sub { } );

# $bot->add_handler(['002','003'], \&dump_event);

# Another way to do it with anonymous sub
$bot->add_handler (
     'JOIN'                                                                         ,
     sub { $conn->notice( $_[1]->nick, 'Hello! I\'m using Net::IRC2 perl module.' ) ; 
	   $_[1]->dump                                                              ;
           print $conn->{'chans'}[0]                                                ;
           print "\n"                                                               }
     ) ;

# Call end_of_motd on IRC messages 376 from the connection $conn
$conn->add_handler(['376'],\&end_of_motd);

# THIS IS WORK ONLY ON MY BOX
# $conn->add_handler(['PING'],\&cpan_upload);

# Ready to rumble !!!
print "START\n";
$bot->start;

sub dump_event { 
    $_[1]->dump;
}
sub end_of_motd {
    # Join some chan
    $conn->join('#Bot,#perl');
    # Say something
#    $conn->privmsg('#Bot', 'Perl module Net::IRC2 v '. $Net::IRC2::VERSION .' is released. http://search.cpan.org/~knotty/Net-IRC2/ . Enjoy!');
#    $conn->privmsg('knotty', 'Perl module Net::IRC2 v '. $Net::IRC2::VERSION .' is released. http://search.cpan.org/~knotty/Net-IRC2/ . Enjoy!');
}

# THIS IS WORK ONLY ON MY BOX DON'T LOOSE YOUR TIME WITH IT !!!!
sub cpan_upload {
    my ( $filename, $handle, $line, $distro );
    while ( $filename = <Maildir/*S> ) {
	open $handle, "<$filename" or warn "\n\n*** Bad Karma ***" and return 0 ;
	while ( $line = <$handle> ) {
	    next unless $line =~ /^Subject: PAUSE upload - (.*)$/ ;
	    $distro = $1 ;
	    last ;
	}
	while ( $line = <$handle> ) {
	    next unless $line =~ /^Request entered by: (\w*) \(/ ;
	    close $filename ;
	    $conn->privmsg('#bot' , "CPAN Upload: $distro by $1" ) ;
	    $conn->privmsg('#perl', "CPAN Upload: $distro by $1" ) ;	    
	    return 0;
	}
    }
}

# Another way to set a callback. This is experimental!
# Should set a callback on ALL connections
sub Net::IRC2::Connection::cb001{ $_[1]->dump }


exit 0;
