# NOTE: I dislike autorejoin, but this seemed like a good script to
# use while I'm learning.
# I also took care of cras' TODO note on his script :)
#
# /set autorejoin_after_seconds 5
# rejoin after X seconds. default is 5
#
# /set autorejoin_channels #channel #channel2
# space delimited list of channels which you would like to autorejoin

use strict;
use Irssi;
use Irssi::Irc;

use vars qw($VERSION %IRSSI);
$VERSION = "0.9";
%IRSSI = (
	authors		=> "David O\'Rourke",
	contact		=> "phyber at EFNet \#irssi",
	name		=> "autorejoin2",
	description	=> "Auto-Rejoin specified channels. Based on autorejoin.pl by Timo 'cras' Sirainen and Leszek Matok.",
	license		=> "GPLv2",
	changed		=> "10.7.2003 18:19"
);

# define some stuff
my @tags;
my $acttag = 0;
my $chanvalid = 0;

sub rejoin {
	my ($data) = @_;
	my ($tag, $servtag, $channel, $key) = split(/ +/, $data);

	my $server = Irssi::server_find_tag($servtag);
	$server->send_raw("JOIN $channel $key") if ($server);
	Irssi::timeout_remove($tags[$tag]);
	# reset this to 0 for next time it's ran
	$chanvalid = 0;
}

sub event_rejoin_kick {
	# split out the server info from the data
	my ($server, $data) = @_;
	# get the channel of the kick and the nick kicked
	my ($channel, $nick) = split(/ +/, $data);
	
	# die if it was somebody else that was kicked
	return if ($server->{nick} ne $nick);
	
	# ok, let's see if we should auto rejoin this channel
	for my $checkchan (split(/ /, Irssi::settings_get_str('autorejoin_channels'))) {
		if ($channel eq $checkchan) {
			$chanvalid = 1;
			last;
		}
	}
	# if not a valid channel, die
	return if ($chanvalid == 0);
	
	# check if the channel has a password
	my $chanrec = $server->channel_find($channel);
	# find the channel key and set $chanrejoin only if $chanrec was found
	my $chankey = $chanrec->{key} if ($chanrec);
	my $chanrejoin = $chanrec->{name} if ($chanrec);
	my $servtag = $server->{tag};
	my $rejoin_delay = Irssi::settings_get_int('autorejoin_after_seconds');
	
	Irssi::print "Rejoining $chanrejoin in $rejoin_delay seconds.";

	# start a "timer" here, keep attempting to rejoin until we get back in.
	# at least, I think that's what this does.
	$tags[$acttag] = Irssi::timeout_add($rejoin_delay * 1000, "rejoin", "$acttag $servtag $chanrejoin $chankey");
	$acttag++; # increment $acttag if join failed.
	$acttag = 0 if ($acttag > 60);
}

Irssi::settings_add_int('autorejoin', 'autorejoin_after_seconds', '5');
Irssi::settings_add_str('autorejoin', 'autorejoin_channels', '');

Irssi::signal_add('event kick', 'event_rejoin_kick');

