#! /usr/bin/perl
#
# xc-cleanlinkchan.pl -- xchat2 script to clean up after linkchan-bot
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# Version: xc-cleanlinkchan.pl 0.1.2  5-May-2006  wnd@iki.fi

# As the name suggests, this script is an X-Chat implementation of
# cleanlinkchan.pl, a script for irssi, by Jari Kohvakka.

use strict;
use warnings FATAL => 'all';

# only process messages coming from here
my $linkmask = "_^_!nikanj\@blue.zerodistance.fi";



sub privmsg_cb
{
	my $r_from = $_[0][0];
#	my $r_action = $_[0][1];
#	my $r_target = $_[0][2];
#	my $r_msg = $_[0][3];

	return Xchat::EAT_NONE if ($_[0][0] ne ":$linkmask");
	
	my ($action, $target, $msg) = $_[1][1] =~ /(.*?) (.*?) :(.*)/;
	# only parse PRIVMSG from linkchan -- there shouldn't be anything else
	my ($first, $second) = $msg =~ /^(.)(.)/;

	# normal message?
	if ($first eq "<") {
		my ($mode, $nick, $text) = $msg =~ /<(.)(.*?)> (.*)/;
		return Xchat::EAT_NONE if (! defined($text));
		Xchat::emit_print("Channel Message",
				($nick, $text, $mode, $text));
		return Xchat::EAT_ALL;
	}

	# user action?
	if ($first eq " " && $second eq "*") {
		my ($nick, $text) = $msg =~ / \* (.*?) (.*)/;
		return Xchat::EAT_NONE if (! defined($text));
		Xchat::emit_print("Channel Action", ($nick, $text, ""));
		return Xchat::EAT_ALL;
	}

	# channel action?
	if ($first eq "-") {
		my ($nick, $host, $chan, $reason, $newnick);

		# join?
		($nick, $host, $chan) = $msg =~
				/-!- (.*) \[(.*?)\] has joined (.*)/;
		if (defined($chan)) {
			Xchat::emit_print("Join", ($nick, $chan, $host));
			return Xchat::EAT_ALL;
		}

		# quit?
		($nick, $host, $reason) = $msg =~
				/-!- (.*?) \[(.*?)\] has quit \[(.*)\]/;
		if (defined($reason)) {
			Xchat::emit_print("Quit", ($nick, $reason, $host));
			return Xchat::EAT_ALL;
		}

		# nick change?
		($nick, $newnick) = $msg =~ /-!- (.*?) is now known as (.*)/;
		if (defined($newnick)) {
			Xchat::emit_print("Change Nick", ($nick, $newnick));
			return Xchat::EAT_ALL;
		}
	}

	return Xchat::EAT_NONE;
}



Xchat::register("xc-cleanlinkchan", "0.1.2",
	"Removes double nicks caused by linkchan.pl");

Xchat::hook_server("PRIVMSG", "privmsg_cb");

Xchat::printf("xc-cleanlinkchan loaded");
