#!/usr/local/bin/perl

# These are the variables passed to each function call.
#
# $_[0] = name for this module (surely you already know this, but still)
# $_[1] = sending nickname
# $_[2] = sending username
# $_[3] = sending hostmask
# $_[4] = sending channel (or botnick in case of PM)
# $_[5] = current value for $modchan
# $_[6] = current value for $botnick
# $_[7] = arguments given in IRC

# The package name must match the filename + .pm, so this file should be called "demo.pm".
package flood;

# Hash tables to hold most recent lines
my %lastline = ();
my %repeats = ();
my %figletline = ();

# Channel to check
my $chan = "#hackerthreads";

# Max repeats
my $max = 3;

# Receive messages
sub mesg {
	# See if we're in the right channel
	if( $_[4] =~ /$chan/ ) {
		my $user = lc $_[1];
		
		# See if we have anything for this user.
		my $found = 0;
		for my $key (keys(%lastline)) {
			if( $key eq $user ) { $found = 1; }
		}

		my $line = $_[7];
		$line =~ s/\s+//g;

		# Check flood
		if( $found == 1 ) {
			if( $lastline{$user} eq $line ) {
				$repeats{$user} += 1;
				
				if( $repeats{$user} >= $max ) {
					nanobot::snd("KICK $chan $_[1] Flooding.");
					$repeats{$user} = 0;
					$figletline{$user} = 0;
				}
			} else {
				$lastline{$user} = $line;
				$repeats{$user} = 1;
			}
		} else {
			$lastline{$user} = $line;
			$repeats{$user} = 1;
			$figletline{$user} = 0;
		}

		# On to figlet
                my $total = 0;
                my $len = length($_[7]);

                if($len > 5) {
                        $total++ while ($_[7] =~ / |_|\\|\/|\-|#|\(|\)|\||@|8|\./g);
                        my $p = ($total / $len)*100;

                        if($p > 75) {
				if( $figletline{$user} == 1) {
					nanobot::snd("KICK $_[4] $_[1] Figlet.");
					$repeats{$user} = 0;
					$figletline{$user} = 0;
				} else {
					$figletline{$user} = 1;
				}
                        } else {
				$figletline{$user} = 0;
			}
		}
	}
}

# Define public functions
sub public {
	@public = ("help");
}

# Brief info about this module
sub help {
	nanobot::ntc($_[1], "Non-interactive module to control flooding and figlet.");
	nanobot::ntc($_[1], "!flood.channel #channel");
	nanobot::ntc($_[1], "!flood.max max repeating lines");
}

# Change the channel
sub channel {
	$chan = $_[7];
	nanobot::ntc($_[1], "Flood channel is now $chan");
}

# Change max lines
sub max {
	$max = $_[7];
	nanobot::ntc($_[1], "Flood max is now $max");
}

# A module must always end with the line "1;", Perl demands it.
1;
