#!/usr/bin/perl
#
# Test for debian/scripts/convert-ban-databases.
#
# usage: convert-ban-databases [CONVERTER]
#   CONVERTER defaults to the installed
#   /usr/share/ircd-hybrid/scripts/convert-ban-databases
#
# The binary ban databases are written on the fly in the format of
# src/conf_db.c in ircd-hybrid 8.2.46 (big-endian uint32 version and
# record count; strings as a uint32 length that includes the trailing NUL,
# 0 meaning NULL; timestamps as uint64), and the expected output is
# inline below, so that no binary test data needs to be shipped.
#
# The converter refuses to run as root, so when started as root this
# checks that refusal, then runs the remaining tests as nobody.
#
# Only uses perl-base, so it can run as an autopkgtest with nothing but
# ircd-hybrid and Essential packages installed.

use strict;
use warnings;

my $converter = shift // '/usr/share/ircd-hybrid/scripts/convert-ban-databases';

# Without the converter every test would fail on its own; stop at once
# with a clear message instead (this also runs again in the re-run as
# nobody, where an unreadable path fails).
if (!-f $converter || !-r _) {
    print "Bail out! converter not found or not readable: $converter\n";
    exit 2;
}
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 is {
    my ($got, $want, $name) = @_;
    return 1 if ok(defined $got && $got eq $want, $name);
    print "#   got:\n", map("#     $_\n", split /\n/, $got // '(undef)', -1);
    print "#   expected:\n", map("#     $_\n", split /\n/, $want, -1);
    return 0;
}

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

sub spew {
    my ($path, $data) = @_;
    open(my $fh, '>:raw', $path) or die "can't write $path: $!\n";
    print $fh $data;
    close $fh or die "can't write $path: $!\n";
}

sub tempdir {
    chomp(my $d = `mktemp -d`);
    die "mktemp -d failed\n" if $? || !-d $d;
    return $d;
}

# Removes the files a test created in its directory, then the directory.
sub cleanup {
    my ($dir) = @_;
    unlink grep { -f $_ || -l $_ } glob("$dir/* $dir/.[!.]*");
    rmdir $dir or print "# couldn't remove $dir: $!\n";
}

# Runs the converter; returns (exit status, stdout, stderr), with the
# test directory replaced by DIR in the output.
sub run {
    my ($dir, @args) = @_;
    my $out = "$dir/.stdout";
    my $err = "$dir/.stderr";
    my $pid = fork() // die "fork: $!\n";
    if ($pid == 0) {
        open(STDOUT, '>', $out) or die "stdout: $!\n";
        open(STDERR, '>', $err) or die "stderr: $!\n";
        exec($^X, $converter, @args) or die "exec $converter: $!\n";
    }
    waitpid($pid, 0);
    my $status = $? >> 8;
    my @text = map { my $t = slurp($_) // ''; unlink $_; $t =~ s/\Q$dir\E/DIR/g; $t } $out, $err;
    return ($status, @text);
}

# The old binary format.
sub u32 { pack('N', $_[0]) }
sub u64 { pack('NN', int($_[0] / 2**32), $_[0] % 2**32) }
sub str {
    my ($s) = @_;
    return u32(0) unless defined $s;
    return u32(length($s) + 1) . $s . "\0";
}
sub db {
    my (%a) = @_;
    my $records = $a{records} // [];
    return u32($a{version} // 1) . u32($a{count} // scalar @$records)
         . join('', @$records) . ($a{tail} // '');
}

# Expected output is written with "<XX>" standing for the byte 0xXX, so
# that this file stays ASCII; everything else is literal.
sub bytes { my ($s) = @_; $s =~ s/<([0-9A-F]{2})>/chr(hex $1)/ge; return $s }

my $T = 1700000000;

########################################################################
# Root: the converter must refuse to run, and write nothing.
########################################################################

if ($> == 0) {
    my $dir = tempdir();
    spew("$dir/kline.db", db(records => [str('*') . str('192.0.2.1') . str('r') . u64($T) . u64(0)]));
    my ($status, $out, $err) = run($dir, $dir);
    is($status, 64, 'as root: exit status 64');
    is($out, '', 'as root: nothing on stdout');
    ok($err =~ /refusing to run as root; run it as the irc user/, 'as root: says why it refuses');
    ok(!-e "$dir/kline.json", 'as root: no kline.json written');
    ($status) = run($dir, '--help');
    is($status, 64, 'as root: --help is refused too');
    ($status) = run($dir, '--dry-run', $dir);
    is($status, 64, 'as root: --dry-run is refused too');
    cleanup($dir);

    # Run everything else as nobody, which needs to read this file and the
    # converter.
    print "# re-running the remaining tests as nobody\n";
    my ($self, $conv) = map { m{^/} ? $_ : do { chomp(my $cwd = `pwd`); "$cwd/$_" } } $0, $converter;
    my $rc = system('runuser', '-u', 'nobody', '--', 'env', '-u', 'TMPDIR',
                    $^X, $self, $conv);
    $rc = $rc == -1 ? 1 : $rc >> 8;
    print "# $passed passed, $failed failed as root\n";
    exit($failed || $rc ? 1 : 0);
}

########################################################################
# Edge cases: everything the converter has to skip, recode or survive.
########################################################################

{
    my $dir = tempdir();
    spew("$dir/kline.db", db(records => [
        str('*') . str('192.0.2.1') . str('plain') . u64($T) . u64(0),
        str('~bad*') . str('*.example.net') . str('quotes " and \\ backslash') . u64($T) . u64($T + 3600),
        str('u') . str('h1') . str("UTF-8 caf\xC3\xA9 \xE2\x98\x83") . u64($T) . u64(0),
        str('u') . str('h2') . str("Latin-1 caf\xE9") . u64($T) . u64(0),
        str('u') . str('h3') . str(undef) . u64($T) . u64(0),
        str('u') . str('h4') . str("tab\there ctl\x01\x7F") . u64($T) . u64(0),
        str('u') . str('h5') . str("embedded\0NUL") . u64($T) . u64(0),
        str("bad\xFF") . str('h6') . str('invalid UTF-8 user') . u64($T) . u64(0),
        str(undef) . str('h7') . str('NULL user') . u64($T) . u64(0),
        str('u') . str('h8') . str('timestamp too big') . u64($T) . u64(2**63),
    ]));
    spew("$dir/dline.db", db(records => [
        str('192.0.2.0/24') . str('v4') . u64($T) . u64(0),
        str('2001:db8::/32') . str('v6') . u64($T) . u64($T + 60),
    ], tail => "\x01\x02\x03"));
    spew("$dir/xline.db", db(count => 3, records => [
        str('badgecos*') . str('x1') . u64($T) . u64(0),
        str('spam bot*') . str('x2') . u64($T) . u64(0),
        str('cut') . str('off'),
    ]));
    spew("$dir/resv.db", db(version => 2));
    my %before = map { $_ => slurp("$dir/$_.db") } qw(kline dline xline resv);

    my ($status, $out, $err) = run($dir, $dir);
    is($status, 2, 'edge cases: exit status 2 (some entries not converted)');
    is($out, <<'EOF', 'edge cases: stdout');
kline: wrote DIR/kline.json (7 of 10 entries, 3 skipped, 1 reason(s) converted from Latin-1)
dline: wrote DIR/dline.json (2 of 2 entries)
xline: wrote DIR/xline.json (2 of 2 entries)
EOF
    is($err, <<'EOF', 'edge cases: stderr');
kline: skipping "bad\xFF": the user is not valid UTF-8, which ircd-hybrid 8.2.47 can't store
kline: skipping an entry with an empty user
kline: skipping "h8": timestamp out of range
dline: DIR/dline.db: 3 trailing bytes ignored
xline: DIR/xline.db: truncated in record 3 of 3
resv: DIR/resv.db: unsupported version 2, not converted
EOF
    is(slurp("$dir/kline.json"), bytes(<<'EOF'), 'edge cases: kline.json');
{
    "k_lines": [
        {
            "user": "*",
            "host": "192.0.2.1",
            "reason": "plain",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "user": "~bad*",
            "host": "*.example.net",
            "reason": "quotes \" and \\ backslash",
            "created_at": 1700000000,
            "expires_at": 1700003600
        },
        {
            "user": "u",
            "host": "h1",
            "reason": "UTF-8 caf<C3><A9> <E2><98><83>",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "user": "u",
            "host": "h2",
            "reason": "Latin-1 caf<C3><A9>",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "user": "u",
            "host": "h3",
            "reason": "<No reason supplied>",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "user": "u",
            "host": "h4",
            "reason": "tab\there ctl\u0001\u007f",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "user": "u",
            "host": "h5",
            "reason": "embedded",
            "created_at": 1700000000,
            "expires_at": 0
        }
    ]
}
EOF
    is(slurp("$dir/dline.json"), <<'EOF', 'edge cases: dline.json');
{
    "d_lines": [
        {
            "host": "192.0.2.0/24",
            "reason": "v4",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "host": "2001:db8::/32",
            "reason": "v6",
            "created_at": 1700000000,
            "expires_at": 1700000060
        }
    ]
}
EOF
    is(slurp("$dir/xline.json"), <<'EOF', 'edge cases: xline.json keeps the records before the truncation');
{
    "x_lines": [
        {
            "mask": "badgecos*",
            "reason": "x1",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "mask": "spam bot*",
            "reason": "x2",
            "created_at": 1700000000,
            "expires_at": 0
        }
    ]
}
EOF
    ok(!-e "$dir/resv.json", 'edge cases: no resv.json for an unreadable database');
    for my $f (qw(kline dline xline)) {
        my $mode = (stat "$dir/$f.json")[2] & 07777;
        is(sprintf('%04o', $mode), '0600', "edge cases: $f.json has mode 0600");
    }
    for my $f (qw(kline dline xline resv)) {
        ok(slurp("$dir/$f.db") eq $before{$f}, "edge cases: $f.db left unchanged");
    }
    ok(!grep({ /\.tmp\./ } glob("$dir/*")), 'edge cases: no temporary files left behind');
    cleanup($dir);
}

########################################################################
# A clean conversion: --dry-run, conversion, re-running, --force.
########################################################################

{
    my $dir = tempdir();
    spew("$dir/kline.db", db(records => [
        str('*') . str('*.example.org') . str('spam') . u64($T) . u64(0),
    ]));
    spew("$dir/dline.db", db());    # valid, no records
    spew("$dir/resv.db", db(records => [
        str('#badchan') . str('channel resv') . u64($T) . u64(0),
        str('badnick*') . str('nick resv') . u64($T) . u64($T + 86400),
    ]));
    # no xline.db: nothing to do for it

    my ($status, $out, $err) = run($dir, '--dry-run', $dir);
    is($status, 0, 'dry run: exit status 0');
    is($out, <<'EOF', 'dry run: stdout');
kline: would write DIR/kline.json (1 of 1 entries)
dline: would write DIR/dline.json (0 of 0 entries)
resv: would write DIR/resv.json (2 of 2 entries)
EOF
    is($err, '', 'dry run: nothing on stderr');
    ok(!grep({ -e "$dir/$_.json" } qw(kline dline xline resv)), 'dry run: no .json written');

    ($status, $out, $err) = run($dir, $dir);
    is($status, 0, 'conversion: exit status 0');
    is($out, <<'EOF', 'conversion: stdout');
kline: wrote DIR/kline.json (1 of 1 entries)
dline: wrote DIR/dline.json (0 of 0 entries)
resv: wrote DIR/resv.json (2 of 2 entries)
EOF
    is($err, '', 'conversion: nothing on stderr');
    is(slurp("$dir/kline.json"), <<'EOF', 'conversion: kline.json');
{
    "k_lines": [
        {
            "user": "*",
            "host": "*.example.org",
            "reason": "spam",
            "created_at": 1700000000,
            "expires_at": 0
        }
    ]
}
EOF
    is(slurp("$dir/dline.json"), <<'EOF', 'conversion: dline.json with no entries');
{
    "d_lines": [
    ]
}
EOF
    is(slurp("$dir/resv.json"), <<'EOF', 'conversion: resv.json');
{
    "resv": [
        {
            "mask": "#badchan",
            "reason": "channel resv",
            "created_at": 1700000000,
            "expires_at": 0
        },
        {
            "mask": "badnick*",
            "reason": "nick resv",
            "created_at": 1700000000,
            "expires_at": 1700086400
        }
    ]
}
EOF
    ok(!-e "$dir/xline.json", 'conversion: no xline.json without an xline.db');

    # Re-running must not overwrite anything.
    spew("$dir/kline.json", "kept\n");
    ($status, $out, $err) = run($dir, $dir);
    is($status, 1, 're-run: exit status 1 (left alone)');
    is($out, '', 're-run: nothing on stdout');
    is($err, <<'EOF', 're-run: stderr');
kline: DIR/kline.json already exists, not converting DIR/kline.db (use --force to overwrite)
dline: DIR/dline.json already exists, not converting DIR/dline.db (use --force to overwrite)
resv: DIR/resv.json already exists, not converting DIR/resv.db (use --force to overwrite)
EOF
    is(slurp("$dir/kline.json"), "kept\n", 're-run: existing kline.json not overwritten');

    ($status, $out, $err) = run($dir, '--force', $dir);
    is($status, 0, '--force: exit status 0');
    ok(slurp("$dir/kline.json") =~ /"host": "\*\.example\.org"/, '--force: kline.json rewritten');
    cleanup($dir);
}

########################################################################
# Damaged files.
########################################################################

{
    my $dir = tempdir();
    spew("$dir/kline.db", '');                 # empty file
    spew("$dir/dline.db", u32(1));             # version, but no count
    my ($status, $out, $err) = run($dir, $dir);
    is($status, 2, 'damaged: exit status 2');
    is($out, '', 'damaged: nothing on stdout');
    is($err, <<'EOF', 'damaged: stderr');
kline: DIR/kline.db: empty or truncated header, not converted
dline: DIR/dline.db: missing record count, not converted
EOF
    ok(!-e "$dir/kline.json" && !-e "$dir/dline.json", 'damaged: no .json written');
    cleanup($dir);
}

########################################################################
# Usage errors.
########################################################################

{
    my $dir = tempdir();
    my ($status, $out, $err) = run($dir, '--bogus');
    is($status, 64, 'usage: unknown option gives exit status 64');
    ok($err =~ /^Unknown option --bogus\nUsage: runuser -u irc -- /, 'usage: says so and prints the usage');
    ($status) = run($dir, $dir, $dir);
    is($status, 64, 'usage: more than one directory gives exit status 64');
    cleanup($dir);
}

print "# $passed passed, $failed failed\n";
exit($failed ? 1 : 0);
