#!/usr/bin/perl
#
# Copyright 2011 by Jan Vales <jan@jvales.net> (Someone <someone@somenet.org>)
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# consider using pybots IRCStats module instead!

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();
}

