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

use Irssi;

my $current = undef;

# /whokill [-yes] [-ops] mask [reason]
Irssi::command_bind 'whokill' => sub {
	my($cmd, $server) = @_;

	unless(ref $server) {
		Irssi::print("No active server");
		return;
	}

	if(defined $current) {
		Irssi::print("Another /whokill is in progress");
		return;
	}

   my(%params, @args);
   while($cmd =~ s/^-([^ ]+) ?//) {
 		$params{$1}++;
 	}
 	while($cmd =~ s/^("[^"]+"|[^ ]+) ?//) {
	   (my $arg = $1) =~ s/(^"|"$)//g;
 		push @args, $arg;
   }

	unless(@args) {
		Irssi::print("No /who mask provided");
		return;
	}

	my $mask   = $args[0];
	my $reason = $args[1] or "bye bye";

	$server->redirect_event("who", 1, "", 0, undef, {
			"event 352" => "redir whokillitem",
			"event 315" => "redir whokillend",
			"event 403" => "redir whokillend",
			"" => "event empty"
		}
	);

	$server->send_raw("WHO $mask");

	$current = {
		yes    => $params{yes},
		ops    => $params{ops},
		mask   => $mask,
		reason => $reason,
		users  => [ ],
	};

	Irssi::print("Sent WHO command for whokill of $mask");
};

Irssi::signal_add 'redir whokillitem' => sub {
	my($server, $data) = @_;

	my($nick, $flags) = (split / /, $data, 9)[5,6];

	if($flags =~ /\*/) {
		Irssi::print("$nick is an oper, not killing");
		return;
	}

	if($flags =~ /\@/ && !$current->{ops}) {
		Irssi::print("$nick is a channel op, not killing (override with -ops)");
		return;
	}

	push @{ $current->{users} }, $nick;
};

Irssi::signal_add 'redir whokillend' => sub {
	my($server, $data) = @_;
	my $count = scalar @{$current->{users}};

	if($current->{yes}) {
		Irssi::print("Killing $count user" . ($count == 1 ? "" : "s"));
		while(@{$current->{users}}) {
			$server->send_raw("KILL " . 
					join(",", splice(@{$current->{users}}, 0, 20))
					. " :$current->{reason}");
		}
	}else{
		Irssi::print("If you had added -yes you would have killed $count user" .
			  ($count == 1 ? "" : "s") . " in total:");
		Irssi::print(join(",", @{$current->{users}}));
	}

	$current = undef;
};

