#!/usr/bin/env perl
# -*- Mode: CPerl;
# cperl-indent-level: 4;
# cperl-continued-statement-offset: 4;
# cperl-indent-parens-as-block: t;
# cperl-tabs-always-indent: t;
# cperl-indent-subs-specially: nil;
# -*-
# vim:ts=4:sw=4:expandtab

# To make development easier.
use lib qw(lib);

use Kanla::Plugin;
use Kanla::Plugin::Banner;

my @ircds;
if (!$conf->is_array('ircd')) {
    @ircds = ($conf->value('ircd'));
} else {
    @ircds = $conf->array('ircd');
}

# Unless the user specified something else,
# we use 45 s instead of the default
# since IRC uses timeouts
# e.g. for ident checking.
if (!$conf->exists('timeout')) {
    $conf->value('timeout', 45);
}

sub run {
    for my $ircd (@ircds) {

        # Connect to each configured server.
        banner_connect(
            host            => $ircd,
            default_service => 'ircd',
            cb              => sub {
                my ($handle, $timeout) = @_;

                # To avoid
                # "nickname already in use"
                # we generate a sufficiently random nick.
                # Downside:
                # This might make kanla health checks
                # look like IRC spam bots.
                # Then again,
                # the network operator(s)
                # should know about any kanla instances.
                my $suffix = '';
                for (1 .. 6) {
                    $suffix .= chr(ord('A') + rand(ord('Z') - ord('A')));
                }
                $handle->push_write("NICK kanla-$suffix\r\n");
                $handle->push_write("USER kanla kanla kanla :kanla\r\n");
                my @read_line;
                @read_line = (
                    line => sub {
                        my ($handle, $line) = @_;
                        if ($line =~ /^PING :?(.+)/) {
                            $handle->push_write("PONG $1\r\n");
                            $handle->push_read(@read_line);
                            return;
                        }
                        if ($line !~ /^:[^ ]+ 001 /) {
                            $handle->push_read(@read_line);
                            return;
                        }

                        # We successfully signed on.
                        undef $timeout;
                        $handle->push_write(
"QUIT :kanla is configured to health-check this server\r\n"
                        );
                        banner_disconnect($handle);
                    });

                $handle->push_read(@read_line);
            });
    }
}
