# Copyright 2002 by Marco d'Itri <md@linux.it>
# You can use this software under the terms of the GNU General Public License.
# use lenght 0 for a permanent kline

use Irssi;
use strict;

use vars qw($VERSION %IRSSI);

$VERSION = '20020128';
%IRSSI = (
	authors		=> 'Marco d\'Itri',
	contact		=> 'md@linux.it',
	name		=> 'masskline',
	description	=> 'read from a file a list of users and kline them',
	license		=> 'GPL v2',
	url			=> 'http://www.linux.it/~md/irssi/',
);

Irssi::command_bind('masskline' => 'cmd_masskline');

sub cmd_masskline {
	my ($params, $server, $winit) = @_;

	my ($file, $length, $reason) = split(/\s+/, $params, 3);
	if (not defined $file or (defined $length and $length !~ /^\d+$/)) {
		Irssi::print('### Usage: /masskline file length reason');
		return;
	}

	$length ||= 60 * 24 * 2;
	$reason ||= 'clonebots not allowed on OPN, please email support@freenode.net if you have any questions';
	
	my @klines = read_hostmasks($file);

	foreach (@klines) {
		#Irssi::print("=> $_"); next; # XXX debugging
		if ($length == 0) {
			$server->send_raw("KLINE $_ :$reason");
		} else {
			$server->send_raw("KLINE $length $_ :$reason");
		}
	}
}

sub read_hostmasks {
	my ($file) = @_;

	if (not open(KFILE, $file)) {
		Irssi::print("### Cannot open $file: $!");
		return;
	}
	
	my @list;
	while (<KFILE>) {
		s/\r?\n?$//;
		next if /^$/;

		m/
##			[a-zA-Z][a-zA-Z0-9\Q[]{}`^-\E\\]+!		# RFC 1459
##			[a-zA-Z0-9\Q[]{}`^_-\E\\]+!				# real world
			(?:\[|\.{2,}|\s)
			~?[a-zA-Z0-9\Q|[]{}`^_-\E\\]{1,16}\@
			(
				(?:
					(?:[a-zA-Z0-9\.-]+\.)+[a-z]{2,4}
				|
					\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
				)
			)
			(?:\]|\.{2,}|\s)
		/ox
			if 1;

#		s/^### //;
#		s/:.*$//;
		/^(
			(?:[a-zA-Z0-9\.-]+\.)+[a-z]{2,4}|
			\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
		)$/ox
			if 0;

		if (not $1) {
			Irssi::print("### Cannot parse \"$_\"\n");
			next;
		}
		next if /\.freenode$/;
		push @list, "*\@$1";
	}

	close KFILE;
	return @list;
}

=comment
<< kline 555 :*@host :comment
>> :server.name.opn NOTICE Md :*** Notice -- Md added K-Line for [*@host :comment] [No reason], expiring at 1011776953 (555 minutes)
>> :server.name.opn NOTICE Md :Added K-Line [*@host :comment] to var/dancer-ircd/kline.conf
=cut
