#!/usr/bin/perl
#
# Basic server startup test: after installation the server is running as
# irc (under its systemd unit, where systemd is the init system), has
# written its log, and answers an IRC client on port 6667.
#
# The shipped ircd.conf requires an ident reply from clients, so this
# stops at the server's greeting rather than registering a client.
#
# 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 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('tail', '-n', '20', '/var/log/ircd/ircd-hybrid.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>;
}

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

if ($systemd) {
    # The package's maintainer scripts start the service; give it a moment
    # in case it is still starting.
    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();
    chomp(my $fragment = `systemctl show -P FragmentPath ircd-hybrid`);
    ok($fragment eq '/usr/lib/systemd/system/ircd-hybrid.service',
       "systemd: runs from the package's unit ($fragment)");
    chomp($pid = `systemctl show -P MainPID ircd-hybrid`);
    ok($pid =~ /^[1-9][0-9]*$/, "systemd: has a main process ($pid)") or finish();
} else {
    # Without systemd, maintainer scripts in a test environment may not
    # have been allowed to start the service, so start it if needed.
    print "# systemd is not the init system; using the init script\n";
    my $pidfile = '/run/ircd/ircd-hybrid.pid';
    my $running = sub {
        my $p = slurp($pidfile);
        return ($p && $p =~ /^(\d+)/ && kill(0, $1)) ? $1 : undef;
    };
    if (!$running->()) {
        print "# not running; starting it with /etc/init.d/ircd-hybrid start\n";
        system('/etc/init.d/ircd-hybrid', 'start');
        for (1 .. 30) { last if $running->(); sleep 1 }
    }
    $pid = $running->();
    ok(defined $pid, "init script: server is running" . ($pid ? " ($pid)" : '')) or finish();
}

# The main process is the server, and runs as irc.
my $exe = readlink("/proc/$pid/exe") // '';
ok($exe eq '/usr/sbin/ircd-hybrid', "main process is /usr/sbin/ircd-hybrid ($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 // '?') . ')');

# It answers on port 6667: connect, start registering, and wait for the
# server's first notice.
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, 'accepts a connection on 127.0.0.1:6667') or finish();

print $sock "NICK autopkgtest\r\nUSER autopkgtest 0 * :autopkgtest\r\n";
my ($greeting, $error, $buf) = (undef, undef, '');
my $sel = IO::Select->new($sock);
my $deadline = time + 20;
while (!defined $greeting && !defined $error && time < $deadline) {
    last unless $sel->can_read($deadline - time);
    my $n = sysread($sock, $buf, 4096, length $buf);
    last unless $n;
    while ($buf =~ s/^([^\r\n]*)\r?\n//) {
        my $line = $1;
        print "#   < $line\n";
        $greeting = $line if $line =~ /^:\S+ NOTICE \S+ :\*\*\* /;
        $error = $line if $line =~ /^ERROR /;
    }
}
ok(defined $greeting, 'server sends its greeting notice'
   . (defined $error ? " (it closed the connection instead: $error)" : ''));
print $sock "QUIT :autopkgtest\r\n";
close $sock;

# It could write its log (the systemd unit only allows writes to a few
# directories).
my $log = slurp('/var/log/ircd/ircd-hybrid.log') // '';
ok($log =~ /Server ready\. Running version: ircd-hybrid-/,
   '/var/log/ircd/ircd-hybrid.log records "Server ready"');

finish();
