

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

use Irssi;
use Irssi::Irc;

($VERSION) = '$Revision: 1.10 $' =~ / (\d+\.\d+) /;
$SCRIPT_NAME = 'zikeys';
%IRSSI = (
    authors     => 'zi',
    contact     => 'zi@zi0r.com',
    name        => 'zikeys',
    description => 'Automatically maintains channel keys.',
    license     => 'Public Domain',
);

sub get_key_info {
        my ($string) = @_;
        my ($modeStr, $rest) = split(/ +/, $string, 2);
        my @modeParams = split(/ +/, $rest);
        my $ptr = 0;
        my ($mode, $plusmodes, $args);

        # processing the default_chanmode setting
        foreach my $char (split(//, $modeStr)) {
                if ($char eq "+") {
                        $mode = "+";
                } elsif ($char eq "-") {
                        $mode = "-";
                } else {
                        if (($mode eq "" || $mode eq "+") && $char eq "k") {
                                $plusmodes .= $char;
                                $args .= $modeParams[$ptr++];
                        }
                }
        }

	return $args;
}

sub zikeys_channel_sync {
        my ($channel) = @_;

	my $mode = $channel->{mode};
	my $key = get_key_info($mode);

	return if (!$key);

	my $channame = $channel->{name};
	my $network = $channel->{server}->{tag};

	Irssi::command("CHANNEL ADD $channame $network $key");
}

sub zikeys_mode_changed {
	my ($server, $data) = @_;
	my ($channel, $mode) = split(/ /, $data, 2);

	my $key = get_key_info($mode);

	return if (!$key);

	my $network = $server->{tag};

	Irssi::command("CHANNEL ADD $channel $network $key");
}

Irssi::signal_add_last('channel sync', 'zikeys_channel_sync');
Irssi::signal_add_last("event mode", "zikeys_mode_changed");
