#!/usr/bin/perl
#
# Integration startup test: configure the packaged ircd-hybrid to accept a
# server link from anope, configure anope to speak the hybrid protocol, start
# anope (under its systemd unit, where systemd is the init system), and check
# that it runs as irc, links to ircd-hybrid, writes its log, and answers a
# client messaging NickServ.
#
# Only uses perl-base.

use strict;
use warnings;
use IO::Select;
use IO::Socket::INET;

# Report everything even if the test is cut short, and don't let a
# connection the server closes kill the test with SIGPIPE.
$| = 1;
$SIG{PIPE} = 'IGNORE';

my ($passed, $failed) = (0, 0);

sub ok {
    my ($cond, $name) = @_;
    if ($cond) { $passed++; print "ok - $name\n" }
    else       { $failed++; print "not ok - $name\n" }
    return $cond;
}

sub diag_cmd {
    my (@cmd) = @_;
    print "# \$ @cmd\n";
    print map { "#   $_" } `@cmd 2>&1`;
}

sub anope_logs {
    opendir(my $dh, '/var/log/anope') or return ();
    my @files = sort grep { /^services\.log/ } readdir($dh);
    closedir($dh);
    return map { "/var/log/anope/$_" } @files;
}

sub diagnostics {
    if (-d '/run/systemd/system') {
        diag_cmd('systemctl', '--no-pager', 'status', 'ircd-hybrid');
        diag_cmd('journalctl', '--no-pager', '-n', '40', '-u', 'ircd-hybrid');
        diag_cmd('systemctl', '--no-pager', 'status', 'anope');
        diag_cmd('journalctl', '--no-pager', '-n', '40', '-u', 'anope');
    }
    diag_cmd('tail', '-n', '40', '/var/log/ircd/ircd-hybrid.log');
    for my $log (anope_logs()) {
        diag_cmd('tail', '-n', '40', $log);
    }
}

sub finish {
    diagnostics() if $failed;
    print "# $passed passed, $failed failed\n";
    exit($failed ? 1 : 0);
}

sub slurp {
    my ($path) = @_;
    open(my $fh, '<', $path) or return undef;
    local $/;
    return scalar <$fh>;
}

# Truncate and rewrite in place so the existing ownership and mode
# (root:irc 0640) are preserved.
sub write_in_place {
    my ($path, $content) = @_;
    open(my $fh, '>', $path) or return 0;
    print {$fh} $content or do { close $fh; return 0 };
    return close $fh;
}

sub live_pid {
    my ($pidfile) = @_;
    my $p = slurp($pidfile);
    return ($p && $p =~ /^(\d+)/ && kill(0, $1)) ? $1 : undef;
}

my $systemd = -d '/run/systemd/system';

# Configure ircd-hybrid to allow local test clients without ident/password,
# exempt 127.0.0.1 from connection throttling, and accept a services link
# matching the shipped anope defaults (services.example.com on 127.0.0.1:7000
# with password "mypassword").
my $ircd_conf_path = '/etc/ircd-hybrid/ircd.conf';
my $ircd_conf = slurp($ircd_conf_path);
ok(defined $ircd_conf, "read $ircd_conf_path") or finish();

my $client_auth = <<'EOF';
auth {
	user = "*@127.0.0.1";
	class = "users";
};

EOF
my $auth_inserted = ($ircd_conf =~ s/^auth\s*\{/${client_auth}auth {/m);
ok($auth_inserted, 'added 127.0.0.1 client auth block to ircd.conf') or finish();

$ircd_conf .= <<'EOF';

exempt {
	ip = "127.0.0.1";
};

listen {
	flags = server;
	host = "127.0.0.1";
	port = 7000;
};

connect {
	name = "services.example.com";
	host = "127.0.0.1";
	port = 7000;
	send_password = "mypassword";
	accept_password = "mypassword";
	encrypted = no;
	class = "server";
};

service {
	name = "services.example.com";
};
EOF
ok(write_in_place($ircd_conf_path, $ircd_conf), "updated $ircd_conf_path") or finish();

# Configure anope to use the hybrid protocol module and a TS6 server ID.
my $anope_conf_path = '/etc/anope/services.conf';
my $anope_conf = slurp($anope_conf_path);
ok(defined $anope_conf, "read $anope_conf_path") or finish();

my $proto_set = ($anope_conf =~ s/name\s*=\s*"inspircd3"/name = "hybrid"/);
ok($proto_set, 'configured hybrid protocol module in services.conf') or finish();

my $sid_set = ($anope_conf =~ s/^(\s*)#id\s*=\s*"00A"/${1}id = "00A"/m);
ok($sid_set, 'configured TS6 server id in services.conf') or finish();

ok(write_in_place($anope_conf_path, $anope_conf), "updated $anope_conf_path") or finish();

# Restart ircd-hybrid so it loads the new configuration.
if ($systemd) {
    my $rc = system('systemctl', 'restart', 'ircd-hybrid');
    ok($rc == 0, 'systemd: restarted ircd-hybrid.service') or finish();
    my $state = '';
    for (1 .. 30) {
        chomp($state = `systemctl is-active ircd-hybrid 2>/dev/null`);
        last if $state eq 'active' || $state eq 'failed';
        sleep 1;
    }
    ok($state eq 'active', "systemd: ircd-hybrid.service is active (is $state)") or finish();
} else {
    print "# systemd is not the init system; using init scripts\n";
    system('/etc/init.d/ircd-hybrid', 'stop');
    for (1 .. 15) { last unless live_pid('/run/ircd/ircd-hybrid.pid'); sleep 1 }
    system('/etc/init.d/ircd-hybrid', 'start');
    my $ircd_pid;
    for (1 .. 30) {
        $ircd_pid = live_pid('/run/ircd/ircd-hybrid.pid');
        last if defined $ircd_pid;
        sleep 1;
    }
    ok(defined $ircd_pid, 'init script: ircd-hybrid is running' . ($ircd_pid ? " ($ircd_pid)" : ''))
        or finish();
}

# Wait until ircd-hybrid is listening on the server link port before starting
# anope (otherwise anope would hit retrywait before retrying).
my $probe;
for (1 .. 30) {
    $probe = IO::Socket::INET->new(PeerAddr => '127.0.0.1', PeerPort => 7000,
                                   Proto => 'tcp', Timeout => 5);
    last if $probe;
    sleep 1;
}
ok($probe, 'ircd-hybrid listens on 127.0.0.1:7000') or finish();
close $probe;

# Start anope and verify its service state and process.
my $pid;
if ($systemd) {
    my $rc = system('systemctl', 'restart', 'anope');
    ok($rc == 0, 'systemd: started anope.service') or finish();
    my $state = '';
    for (1 .. 30) {
        chomp($state = `systemctl is-active anope 2>/dev/null`);
        last if $state eq 'active' || $state eq 'failed';
        sleep 1;
    }
    ok($state eq 'active', "systemd: anope.service is active (is $state)") or finish();
    chomp(my $fragment = `systemctl show -P FragmentPath anope`);
    ok($fragment eq '/usr/lib/systemd/system/anope.service',
       "systemd: runs from the package's unit ($fragment)");
    chomp($pid = `systemctl show -P MainPID anope`);
    ok($pid =~ /^[1-9][0-9]*$/, "systemd: has a main process ($pid)") or finish();
} else {
    system('/etc/init.d/anope', 'stop');
    for (1 .. 15) { last unless live_pid('/run/anope/anope.pid'); sleep 1 }
    system('/etc/init.d/anope', 'start');
    for (1 .. 30) {
        $pid = live_pid('/run/anope/anope.pid');
        last if defined $pid;
        sleep 1;
    }
    ok(defined $pid, 'init script: anope is running' . ($pid ? " ($pid)" : '')) or finish();
}

# The main process is anope, running as irc.
my $exe = readlink("/proc/$pid/exe");
if (!defined $exe) {
    # Unprivileged containers without CAP_SYS_PTRACE deny readlink on
    # another UID's /proc/$pid/exe; fall back to argv[0] from cmdline.
    my $cmdline = slurp("/proc/$pid/cmdline") // '';
    ($exe) = split /\0/, $cmdline;
}
$exe //= '';
ok($exe eq '/usr/sbin/anope', "main process is /usr/sbin/anope ($exe)");
my $uid = (stat "/proc/$pid")[4];
my $irc_uid = getpwnam('irc');
ok(defined $uid && defined $irc_uid && $uid == $irc_uid,
   'main process runs as irc (uid ' . ($uid // '?') . ')');

# Check both logs record that the link succeeded.
my ($anope_linked, $ircd_linked) = (0, 0);
for (1 .. 20) {
    if (!$anope_linked) {
        my $log = join('', map { slurp($_) // '' } anope_logs());
        $anope_linked = 1 if $log =~ /Successfully linked/;
    }
    if (!$ircd_linked) {
        my $log = slurp('/var/log/ircd/ircd-hybrid.log') // '';
        $ircd_linked = 1 if $log =~ /Link with services\.example\.com\[[^\]]*\] established:/;
    }
    last if $anope_linked && $ircd_linked;
    sleep 1;
}
ok($anope_linked, '/var/log/anope/services.log.* records "Successfully linked"');
ok($ircd_linked, '/var/log/ircd/ircd-hybrid.log records link established with services.example.com');

# Connect an IRC client to ircd-hybrid, register, and message NickServ to
# confirm end-to-end communication with anope across the link.
my $sock;
for (1 .. 30) {
    $sock = IO::Socket::INET->new(PeerAddr => '127.0.0.1', PeerPort => 6667,
                                  Proto => 'tcp', Timeout => 5);
    last if $sock;
    sleep 1;
}
ok($sock, 'client connects to ircd-hybrid on 127.0.0.1:6667') or finish();

print $sock "NICK testuser\r\nUSER testuser 0 * :autopkgtest\r\n";
my ($registered, $nickserv_reply, $error, $buf) = (0, undef, undef, '');
my $sel = IO::Select->new($sock);
my $deadline = time + 20;
while (!defined $nickserv_reply && !defined $error && time < $deadline) {
    my $remaining = $deadline - time;
    last if $remaining <= 0;
    last unless $sel->can_read($remaining);
    my $n = sysread($sock, $buf, 4096, length $buf);
    last unless $n;
    while ($buf =~ s/^([^\r\n]*)\r?\n//) {
        my $line = $1;
        print "#   < $line\n";
        if ($line =~ /^PING\s+(.+)$/) {
            print $sock "PONG $1\r\n";
        }
        if (!$registered && $line =~ /^:\S+ 001 testuser /) {
            $registered = 1;
            print $sock "PRIVMSG NickServ :HELP\r\n";
        }
        if ($line =~ /^:NickServ!\S+ (?:NOTICE|PRIVMSG) testuser :/i) {
            $nickserv_reply = $line;
        }
        $error = $line if $line =~ /^ERROR /;
    }
}
ok($registered, 'client registered with ircd-hybrid'
   . (defined $error ? " (server closed connection: $error)" : ''));
ok(defined $nickserv_reply, 'NickServ replied to HELP across the ircd-hybrid link');

print $sock "QUIT :autopkgtest\r\n";
close $sock;

finish();
