#!/usr/bin/perl -w

# foXbot. A small ircd stats gathering bot.
# see foXbot.conf for configuration details
# This program connects to an irc server and polls LUSERS
# statistics printing a timestamp, the irc server, current
# number of lusers connected and max lusers.

# Written by Rocco Lucia (rlucia@iscanet.com, http://elisa.utopianet.net/~rlucia )
# Thu May  3 00:10:46 CEST 2001 

# This code is distributed under a BSD style license.  You are free
# to do with it as you please. Yes, I bet you won't live without it.

use Net::IRC;
use Time::localtime;

$| = 1;

$configfile = shift @ARGV || "foXbot.conf";

open( CONFIG, $configfile) or die "Couldn't open configuration file\n";

while(<CONFIG>) {
    chomp;
    s/#.*//;
    s/^\s+//;
    s/\s+$//;
    next unless length;
    my ($var, $value) = split(/\s*=\s*/, $_, 2);
    $bot_prefs{$var} = $value;
}

close(CONFIG);

# $pfile = $bot_prefs{"VARDIR"} . "/" . $bot_prefs{"IRCSERVER"} . ".pid";
# print $pfile, "\n";
# open( PF, $pfile, O_RDWR|O_CREAT ) or die "Error: $!\n";
# print PF $$;
# close(PF);

sub on_connect {
    my $self = shift; 

    alarm($bot_prefs{"POLLINT"});
    if($bot_prefs{"SERVERSPY"} eq "YES") {
      $self->join("&servers");
    };
}

sub on_disconnect {
        my ($self, $event) = @_;

        $self->connect();
}

sub on_nick_taken {
    my ($self) = shift;

    $self->nick(substr($self->nick, -1) . substr($self->nick, 0, 8));
}

sub on_glusers {
    my ($self, $event) = @_;
    my (@args) = ($event->args);
    shift (@args);
    $_ = $args[0];
    ($lusers, $maxusers) = /$bot_prefs{"LUSERSPARSE"}/;
    my $tm = localtime;

    print "LUSERS ";
    printf( "%04d%02d%02d%02d%02d%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);
    print " ", $bot_prefs{"IRCSERVER"}, " ", $lusers, " ", $maxusers, "\n";
}

sub on_notice {
    my ($self, $event) = @_;
    my (@args) = ($event->args);
    my $tm = localtime;
    $now = sprintf( "%04d%02d%02d%02d%02d%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday, $tm->hour, $tm->min, $tm->sec);
    
#    if( ($message, $from, $to, $reason) = /$bot_prefs{"SERVERSPARSE"}/ ) {
#       print "$message $now $from $to $reason\n"
#       return;
#    }

    print "NOTICE $now ", $bot_prefs{"IRCSERVER"}, " $args[0]\n"
}

my $irc = new Net::IRC;

my $conn = $irc->newconn(       Nick    => $bot_prefs{"NICKNAME"},
                Server  => $bot_prefs{"IRCSERVER"},
                Port    => $bot_prefs{"SERVERPORT"},
                Ircname => $bot_prefs{"REALNAME"}) or
        die "foXbot: Can't connect to IRC server.\n";

$conn->add_global_handler(265, \&on_glusers);
$conn->add_global_handler(376, \&on_connect);
$conn->add_global_handler(433, \&on_nick_taken);
$conn->add_global_handler('disconnect', \&on_disconnect);
$conn->add_handler('notice', \&on_notice);

$SIG{ALRM} = sub {
    $conn->lusers;
    alarm($bot_prefs{"POLLINT"});
};

$irc->start;

