#!/usr/bin/perl
require Net::IRC;

mkdir("/tmp/irc", 0775);
open (STATS, '>/tmp/irc/stats.txt');
open (CHANS, '>/tmp/irc/channels.txt');
my $irc = new Net::IRC;
my $conn = $irc->newconn(Nick => 'srv254-stats', Server => 'localhost');
$conn->debug(0);
$conn->add_global_handler('luserclient', \&luserclient);
$conn->add_global_handler('luserchannels', \&luserchannels);
$conn->add_global_handler('endofmotd', \&ask);
$conn->add_global_handler('list', \&list);
$conn->add_global_handler('listend', \&quit);


sub luserclient {
    my($self, $event) = @_;
    if(($event->args)[1] =~  /There are (\d+) users and (\d+) invisible on (\d+) servers/) {
#        printf STATS "".(($event->args)[1])."\n";
        printf STATS "clients.value ".($1 + $2 -1)."\n";
	printf STATS "servers.value $3\n";
    }
}

sub luserchannels {
    my($self, $event) = @_;
    if(($event->args)[1] =~  /^(\d+)/) {
        printf STATS "channels.value $1\n";
    }
}

sub ask {
    my($self, $event) = @_;
    $conn->list();
}

sub list {
    my($self, $event) = @_;
    printf CHANS (($event->args)[1])." ".(($event->args)[2])." ".(($event->args)[3])."\n";
}

sub quit {
    my($self, $event) = @_;
    $self->quit();
    close (STATS);
    close (CHANS);
    exit 0;
}



while(1) {
    $irc->do_one_loop();
}

