# /AUTOBAN <*|#channel> [<nickmasks>]
# BASED on AUTOOP by Timo Sirainen (Public Domain)

use Irssi;
use strict;
use vars qw($VERSION %IRSSI);

$VERSION = "1.0";

%IRSSI = (
    authors     => 'Vesa Tervo (RootBear), Timo Sirainen (original autoop.pl)',
    name        => 'autoban',
    description => 'Simple auto-ban script',
    license     => 'EVVKTVH / Public Domain',
    changed	=> 'Sun Dec 10 10:21 UTC 2006'
);

my (%opnicks, %temp_opped);

sub cmd_autoban {
	my ($data) = @_;
	my ($channel, $masks) = split(" ", $data, 2);

	if ($channel eq "") {
		if (!%opnicks) {
			Irssi::print("Usage: /AUTOBAN <*|#channel> [<nickmasks>]");
			Irssi::print("No-one's being auto-banned currently.");
			return;
		}

		Irssi::print("Currently auto-banning in channels:");
		foreach $channel (keys %opnicks) {
			$masks = $opnicks{$channel};

			if ($channel eq "*") {
				Irssi::print("All channels: $masks");
			} else {
				Irssi::print("$channel: $masks");
			}
		}
		return;
	}

	if ($masks eq "") {
		$masks = "<no-one>";
		delete $opnicks{$channel};
	} else {
		$opnicks{$channel} = $masks;
	}
	if ($channel eq "*") {
		Irssi::print("Now auto-banning in all channels: $masks");
	} else {
		Irssi::print("$channel: Now auto-banning: $masks");
	}
}

sub autoban {
	my ($channel, $masks, @nicks) = @_;
	my ($server, $nickrec);

	$server = $channel->{server};
	foreach $nickrec (@nicks) {
		my $nick = $nickrec->{nick};
		my $host = $nickrec->{host};

                if (!$temp_opped{$nick} &&
		    $server->masks_match($masks, $nick, $host)) {
			$channel->command("/kick $nick tervetuloa uudelleen");
                        $channel->command("/ban $nick");
			$temp_opped{$nick} = 1;
		}
	}
}

sub event_massjoin {
	my ($channel, $nicks_list) = @_;
	my @nicks = @{$nicks_list};

	return if (!$channel->{chanop});

	undef %temp_opped;

	# channel specific
	my $masks = $opnicks{$channel->{name}};
	autoban($channel, $masks, @nicks) if ($masks);

	# for all channels
	$masks = $opnicks{"*"};
	autoban($channel, $masks, @nicks) if ($masks);
}

Irssi::command_bind('autoban', 'cmd_autoban');
Irssi::signal_add_last('massjoin', 'event_massjoin');
