#-------------------------------------------------------------------------------
# $Id: usercount2file.pl 1770 2007-11-14 09:13:06Z jnieuwen $
#-------------------------------------------------------------------------------
# (c) 2007 Jeroen van Nieuwenhuizen
#-------------------------------------------------------------------------------
# The use clauses
#-------------------------------------------------------------------------------
use strict ;

use POSIX qw(strftime);
use Irssi;
use Irssi::Irc;

my $VERSION = '$Id: usercount2file.pl 1770 2007-11-14 09:13:06Z jnieuwen $';
my %IRSSI = (
        "authors"       => "Jeroen van Nieuwenhuizen",
        "contact"       => "contact [at] jeroen [dot] se",
        "name"          => "usercount2file.pl",
        "description"   => "Writes usercounts to a file",
        "url"           => "http://www.jeroen.se",
        "license"       => "GNU GPL v2",
        "changed"       => "2007-11-14"
);


my $g_timer ;
my $g_file = '' ;

#-------------------------------------------------------------------------------
sub truncate_file() {
	open (FILE,">".$g_file) or return 0 ;
	print FILE "server:channel:ircops:ops:halfops:voices:normal:total\n" ;
	close FILE ;
	return 1 ;
}

#-------------------------------------------------------------------------------
sub calc_users {
	my $channel = shift;
	my $server = $channel->{server};
	my $ircops ;
	my $ops ;
	my $halfops ;
	my $voices ;
	my $normal ;

	$ircops = $ops = $halfops = $voices = $normal = 0;
	for ($channel->nicks()) {
		if ($_->{serverop}) {
			$ircops++;
		}
		if ($_->{op}) {
			$ops++;
		} elsif ($_->{halfop}) {
			$halfops++;
		} elsif ($_->{voice}) {
			$voices++;
		} else {
			$normal++;
		}
	}
	my $total = $ops+$halfops+$voices+$normal;
	open(FILE,">>".$g_file) or return 0 ;
	printf FILE "%s:%s:%s:%s:%s:%s:%s:%s\n", $server->{tag},$channel->{name},$ircops,$ops,$halfops,$voices,$normal,$total ;
	close FILE ;
}

#-------------------------------------------------------------------------------
sub do_run {
	$g_file = Irssi::settings_get_str('usercountlog_file')  ;
	if ($g_file ne '') {
		if (truncate_file()) {
			foreach my $channel (Irssi::channels()) {
				calc_users($channel) ;
			}
		}
	}
	if (defined $g_timer) {
		Irssi::timeout_remove($g_timer) ;
		$g_timer = undef ;
	}

	$g_timer = Irssi::timeout_add(60000, "do_run", "");
}

#-------------------------------------------------------------------------------
# MAIN LOOP
#-------------------------------------------------------------------------------

Irssi::settings_add_str("log","usercountlog_file",'');
do_run() ;

