#!/usr/bin/perl -w
# VIM: set ts=4, set sw=4
#
package IRC::XChat::Match;

my $script_name    = "clonesucker.pl";
my $script_version = '0.2';

IRC::register($script_name,$script_version, "", "");
IRC::print("\cC3Plugin CloneSucker caricato!\n");

my $pkg = __PACKAGE__;

IRC::add_command_handler("CLONI",  "${pkg}::cmd_clones");
IRC::add_message_handler("JOIN",   "${pkg}::handle_join");

sub trim {
    local $_ = shift;
    s/^\s*//;
    s/\s*$//;
    return $_;
}

sub irc2perl {
    local $_ = shift;
    s/\@/\\@/g;
    s/\./\\./g;
    s/\*/.*/g;
    s/\?/./g;
    return $_;
}

sub handle_join {
	my $line = shift;
	$line =~ /:([^!]*)![^@]*@([^ ]*)\s+.*?\s*:(\S+)/;
	my ($nick,$host,$chan,$server) = ($1,lc($2),$3,IRC::get_info(3));
	my %userlist = IRC::user_list_short($chan,$server);

	foreach my $user (keys %userlist) {
		$userlist{$user} =~ s/^.*\@//;
		if ($host eq lc($userlist{$user})) {
			IRC::print("\cB\cC4CLONE SUCANTE su \cC4$chan\cO: \n"
                       . "\cB\cC4Clone: $nick\n \cB\cC4User: $user\n \cB\cC4Host: *!*\@$host");
			last;
		}
	}	
	return 0;
}


sub cmd_clones {
    my ($chan,$server) = (IRC::get_info(2),IRC::get_info(3));
    my %userlist       = IRC::user_list_short($chan,$server);
    my %clones         = ();
	my $found_clones   = 0;
	my $need_header    = 1;

    foreach my $nick (keys %userlist) {
        my $host = lc $userlist{$nick};
		next if $host =~ /^FETCHING$/i;
        $host =~ s/^.*\@//;
		push @{$clones{$host}}, $nick;
    }

	foreach my $host (keys %clones) {
		next if (@{$clones{$host}} == 1);
		$found_clones = 1;
		if ($need_header) {
			$need_header = 0;
			IRC::print("\cB\cC4[Sucloni su \cC0\cB$chan\cC4]\n");
		}
		IRC::print("\cB\cC9|\cC0 " . join(", ", @{$clones{$host}}) 
				 . ": *!*\@$host"); 
	}
	IRC::print("SUCLONI: nessun suclone su $chan")
		unless $found_clones;
	return 1;
}

1;
#end
