#! /usr/bin/env perl

use IO::Socket::INET;

my ($reason, $ident, $host);

my (@found, @klines);
my ($last, $lasthost);

my ($irc);

require './settings.pl';

$irc = IO::Socket::INET->new(PeerAddr=>$server, PeerPort=>6667, Proto=>'tcp');
die "$!" if not defined $irc;

print $irc "USER " . $user . " * ". $server . " :kline simplificator\n";
print $irc "NICK " . $nick . "\n";

while (<$irc>) {
	if (/^:$server 001 $nick/) {
		print $irc "OPER " . $opername . " " . $operpass . "\n";
		print $irc "STATS K\n";
		next;
	}
	if (/^:$server 219 $nick K/) {
		print $irc "QUIT :juli's kline simplificator\n";
		next;
	}
	if (!/^:$server 216 $nick K/) {
		next;
	}
	($host, $ident, $reason) =
	    /^:$server 216 $nick K ([^ ]+) \* ([^ ]+) :(.*)/;
	push @klines, $host . ':' . $ident . ':' . $reason;
}

sort @klines;

foreach my $this (@klines) {
	($host) = $this =~ /^([^:]+):/;

	# Check for at least three dots.
	if ($host !~ /.*\..*\..*\./) {
		next;
	}
	if (defined $last) {
		if ($last eq $host) {
			$lasthost = $host;
		} else {
			if (defined $lasthost) {
				push @found, $lasthost;
			}
			$lasthost = undef;
		}
	}
	$last = $host;
}

foreach my $this (@klines) {
	($host, $ident) = $this =~ /^([^:]+):([^:]+):/;

	if (grep { $_ eq $host } @found) {
		print "/quote unkline " . $ident . '@' . $host . "\n";
	}
}

foreach my $this (@found) {
	my (@these);

	@these = grep { $_ =~ /^$this:/ } @klines;
	if (not defined @these) {
		die "ERROR: Unable to find a kline to use for a reason.";
	}
	($reason) = $these[0] =~ /[^:]+:[^:]+:(.*)/;
	if (not defined $reason) {
		die "ERROR: Unable to find a kline reason.";
	}
	print "/quote kline *\@" . $this . ' :' . $reason . "\n";
}
