use Irssi;
use strict;
use vars qw($VERSION %IRSSI $nick $ident $host $channel);

$VERSION = '1.00';
%IRSSI = (
    authors 	=> 'Eric Jansen',
    contact 	=> 'chaos@sorcery.net',
    name 	=> 'maskedban',
    description => 'Ban on masked hostname when opered by typing /maskedban <nick>',
    license 	=> 'GPL',
    modules	=> '',
    url		=> 'http://xyrion.org/irssi/',
    changed 	=> 'Sat Mar  1 13:36:48 CET 2003'
);

sub cmd_maskedban {

    my ($data, $server, $witem) = @_;

    # Strip whitespace surrounding nick
    $data =~ s/^\s*([^\s]+)\s*/$1/;

    # Are we in a channel
    if(!$witem || $witem->{'type'} ne 'CHANNEL') {

	Irssi::print("Not in a channel");
	return;
    }

    # Use the normal /ban unless we are opered
    elsif($witem->{'server'}->{'server_operator'} == 0) {

	$witem->command("ban $data");
	return;
    }

    # Remember the channel name for future use
    else {

	$channel = $witem->{'name'};
    }

    # Search for the hostname and ask the ircd for the masked version of it
    foreach my $channick ($witem->nicks()) {

	if(lc($channick->{'nick'}) eq lc($data) && $channick->{'host'} =~ /^([^\@]+)\@([^\@]+)$/) {

	    ($nick, $ident, $host) = ($channick->{'nick'}, $1, $2);

	    $server->command("QUOTE SHOWMASK $host");
	    last;
	}
    }
}

sub event_notice {

    my ($server, $text, $from, $address) = @_;

    # Skip non-server notices
    return unless $from eq $server->{'real_address'};

    # Check if it's the reply to our request
    if(defined $host && $text =~ /\s*$host\s+->\s+([^\.]+)\.([^\s]+)/) {

	my ($maskedhost, $maskeddomain) = ($1, $2);
	my $bantype = Irssi::settings_get_str('ban_type');

	# Create a banmask out of it using the setting ban_type
	if($bantype !~ /^custom/i) {

	    $bantype = 'custom user domain' 	if $bantype =~ /^normal$/i;
	    $bantype = 'custom user' 		if $bantype =~ /^user$/i;
	    $bantype = 'custom host domain' 	if $bantype =~ /^host$/i;
	    $bantype = 'custom domain' 		if $bantype =~ /^domain$/i;
	}

	$nick 		= '*' if $bantype !~ /^custom .*nick/i;
	$ident 		= '*' if $bantype !~ /^custom .*user/i;
	$maskedhost 	= '*' if $bantype !~ /^custom .*host/i;
	$maskeddomain 	= '*' if $bantype !~ /^custom .*domain/i;

	# Set the ban
	$server->command("mode $channel +b $nick!$ident\@$maskedhost.$maskeddomain");
	undef $host;

	# Stop the signal from reaching the user
	Irssi::signal_stop();
    }
}

Irssi::command_bind('maskedban', 'cmd_maskedban');
Irssi::signal_add('message irc notice', 'event_notice');
