#!/bin/sh
# $Id$

# cli

. ./sh/lib/setup
. ./sh/lib/repo-setup
. ./sh/lib/rpm-setup

ORIGREPO=
DESTINATION_REPO=
DEPENDENCY_SOLVER=3

setUp() {
    is_rpm_testing_off && return

    rpm_up
    # provide /bin/sh auto requirement
    rpm_build_installed sh -p /bin/sh

    local use_sudo="n"
    [ -n "$SUDO" ] && use_sudo=y

    RAW_POLDEK="$POLDEK_NOCONF -Ouse_sudo=$use_sudo"
    POLDEK="$RAW_POLDEK --st pndir -s $REPO --root $DESTINATION_REPO --justdb"

    $RAW_POLDEK clean
}

tearDown() {
    #rpm_down
}

build() {
    build_package $REPO $@
}

build_installed() {
    rpm_build_installed $@
}

index() {
    $RAW_POLDEK --st dir -s $REPO --index
}

testNoop() {
    return 0
}

testInstall()
{
    skip_if_rpm_testing_off && return

    build a
    index

    msg $POLDEK install -v a
    $POLDEK install -v a
    assertEquals "install failed" "$?" "0"
    rpm_state_check "a" ""
}

testInstallNoConfig()
{
    skip_if_rpm_testing_off && return

    build a
    index

    # any -O option creates a configuration, so run without RAW_POLDEK's ones
    msg $POLDEK_RAW --noconf --cachedir $CACHEDIR --st pndir -s $REPO --root $DESTINATION_REPO -t install -v a
    $POLDEK_RAW --noconf --cachedir $CACHEDIR --st pndir -s $REPO --root $DESTINATION_REPO -t install -v a
    assertEquals "install failed" "$?" "0"
}

testInstallPercentInFileName()
{
    skip_if_rpm_testing_off && return

    build a
    # as saved from a URL with an encoded space; "%20d" must not be read as a conversion
    mv $REPO/a-1-1.noarch.rpm "$REPO/a-1-1%20dev.noarch.rpm" || fail "renaming the package failed"
    index

    msg $POLDEK install -v a
    $POLDEK install -v a
    assertEquals "install failed" "$?" "0"
    rpm_state_check "a" ""
}

# https://github.com/poldek-pm/poldek/issues/27
testInstallAlreadyInstalled() {
    skip_if_rpm_testing_off && return

    msgn "Preparing repositories..."
    build_installed b

    build a
    build b
    index
    $POLDEK up                  # to create stubindex

    msg $POLDEK install -v a b
    $POLDEK install -v a b
    assertEquals "install failed" "$?" "0"
    rpm_state_check "a" ""
}

# an index of a and b with its stub index cut short, in $STUB; with "empty"
# cut before its first write
index_with_cut_stub() {
    build a
    build b
    index
    # the stub index of an index made just now gets an earlier time and is
    # not read at all, cut or not
    touch -d '-1 hour' $REPO/packages.ndir*
    $POLDEK up                  # to create stubindex

    STUB=$(ls $CACHEDIR/*/stubindex.pndir.zst)
    [ -f "$STUB" ] || fail "no stub index"
    if [ "${1:-}" = empty ]; then
        : > $STUB.cut
    else
        # like a large one cut short: the lines before the cut read whole,
        # the line of b is in a frame cut short
        zstdcat $STUB > $STUB.lines || fail "zstdcat failed"
        { grep -v '^b#' $STUB.lines | zstd -q; grep '^b#' $STUB.lines | zstd -q | head -c 10; } > $STUB.cut
        rm -f $STUB.lines
    fi
    touch -r $STUB $STUB.cut        # the file keeps its time
    mv $STUB.cut $STUB
}

# a stub index cut short is not used: install still finds a package that was
# listed after the cut
testInstallStubIndexCut()
{
    skip_if_rpm_testing_off && return

    index_with_cut_stub
    $POLDEK install -v b
    assertEquals "install failed" "$?" "0"
    rpm_state_check "b" ""
}

# a stub index cut short is written again whole, though its time says that it
# is up to date
testStubIndexCutWrittenAgain()
{
    skip_if_rpm_testing_off && return

    index_with_cut_stub
    $POLDEK ls > /dev/null 2>&1
    assertEquals "packages in the stub index" "2" "$(zstdcat $STUB | grep -vc "^%")"
}

# so is one cut before its first write, an empty file
testStubIndexEmptyWrittenAgain()
{
    skip_if_rpm_testing_off && return

    index_with_cut_stub empty
    $POLDEK ls > /dev/null 2>&1
    assertEquals "packages in the stub index" "2" "$(zstdcat $STUB | grep -vc "^%")"
}

# a stub index that could not be written is left as it was: its time is the
# old index's, so the next load writes it again
testStubIndexWriteError()
{
    skip_if_rpm_testing_off && return

    build a
    index
    touch -d '-1 hour' $REPO/packages.ndir*
    $POLDEK up                  # to create stubindex

    local stub=$(ls $CACHEDIR/*/stubindex.pndir.zst)
    [ -f "$stub" ] || fail "no stub index"
    assertEquals "packages in the stub index" "1" "$(zstdcat $stub | grep -vc "^%")"

    build b
    index
    env LD_PRELOAD=$PWD/.libs/close_error.so WRITE_ERROR=stubindex.pndir.zst \
        $POLDEK ls > /dev/null 2>&1
    assertEquals "stub index replaced" "1" "$(zstdcat $stub | grep -vc "^%")"
    left=$(find $(dirname $stub) -name '.*.tmp.??????')
    [ -z "$left" ] || fail "temporary files left: $left"

    $POLDEK ls > /dev/null 2>&1
    assertEquals "packages in the stub index" "2" "$(zstdcat $stub | grep -vc "^%")"
}

# of two packages a source takes for one it gives one, after its masks, which
# may tell them apart by how the version is written; with the stub index the
# choice is the same
testStubIndexOfDuplicates()
{
    skip_if_rpm_testing_off && return

    local conf=$TMPDIR/source-dup.conf mask left cold out cmd

    SOURCE_DATE_EPOCH=$(date -u -d 2021-05-03 +%s)
    export SOURCE_DATE_EPOCH
    build a
    mv $REPO/a-1-1.noarch.rpm $REPO/older.rpm
    build same 1-1
    SOURCE_DATE_EPOCH=$(date -u -d 2024-07-03 +%s)
    build a
    build same 01-1
    unset SOURCE_DATE_EPOCH

    for mask in "" same-01-1 same-1-1; do
        left="same-01-1"
        [ "$mask" = "same-01-1" ] && left="same-1-1"
        printf '[source]\nname = s\ntype = dir\npath = %s/\n' $REPO > $conf
        [ -n "$mask" ] && echo "ignore = $mask" >> $conf
        rm -rf $CACHEDIR

        for cmd in "ls -l a" "ls same" "desc same"; do
            cold=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n s -q --cmd "$cmd" 2>&1 |
                   grep -e '^a-1-1' -e '^same-' -e '^Package:')
            [ -n "$cold" ] || fail "ignore = $mask: $cmd shows nothing"
            out=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n s -q --cmd "$cmd" 2>&1 |
                  grep -e '^a-1-1' -e '^same-' -e '^Package:')
            assertEquals "ignore = $mask: $cmd with the stub index" "$cold" "$out"
            [ "$cmd" = "ls -l a" ] && continue
            echo "$out" | grep -q "$left" || fail "ignore = $mask: $cmd does not show $left ($out)"
        done
    done
}

# a directory index that could not be written is left as it was, with its
# time, so the next load still finds it outdated and writes it again
testDirIndexWriteError()
{
    skip_if_rpm_testing_off && return

    build a
    index
    touch -d '-1 hour' $REPO/packages.ndir*
    $POLDEK up                  # to create dirindex

    local dirindex=$(ls $CACHEDIR/*/dirindex.pndir.tndb)
    [ -f "$dirindex" ] || fail "no dirindex"
    local before=$(cksum < $dirindex) mtime=$(stat -c %Y $dirindex)

    build b
    index
    env LD_PRELOAD=$PWD/.libs/close_error.so WRITE_ERROR=dirindex.pndir.tndb \
        $POLDEK up > /dev/null 2>&1
    assertEquals "dirindex replaced" "$before" "$(cksum < $dirindex)"
    assertEquals "time of the old dirindex changed" "$mtime" "$(stat -c %Y $dirindex)"
    left=$(find $(dirname $dirindex) -name '.*.tmp.??????')
    [ -z "$left" ] || fail "temporary files left: $left"

    $POLDEK up > /dev/null 2>&1
    [ "$(cksum < $dirindex)" != "$before" ] || fail "dirindex not written again"
}

# a record of the directory index that cannot be read (its value length set
# past the end, the index signed again) is reported, and the directory index
# is made again: $1 is the prefix of the key of the record
check_dirindex_broken_record()
{
    build a 1-1 -f /opt/zzdir/data      # so that its directories follow the key map
    index
    $POLDEK up                          # to create dirindex

    local dirindex=$(ls $CACHEDIR/*/dirindex.pndir.tndb)
    [ -f "$dirindex" ] || fail "no dirindex"
    python3 -I $SHLIBDIR/tndb-set-vlen $dirindex "$1" 0xffffffff ||
        fail "tndb-set-vlen failed"
    local broken=$(cksum < $dirindex)

    # in testing mode poldek aborts at a broken dirindex
    local out=$(env -u POLDEK_TESTING $POLDEK -Oauto_directory_dependencies=y ls 2>&1)
    echo "$out" | grep -q 'invalid directory index' ||
        fail "no error for the broken record: $out"
    [ "$(cksum < $dirindex)" != "$broken" ] || fail "the broken dirindex was kept"
    $POLDEK -Oauto_directory_dependencies=y ls > /dev/null 2>&1 ||
        fail "the dirindex made again does not verify"
}

# the first record after the key map, rather than read as a package
# without directories
testDirIndexBrokenRecord()
{
    skip_if_rpm_testing_off && return
    check_dirindex_broken_record '_\a#'
}

# the first record of the key map, rather than read as the end of an
# empty key map
testDirIndexBrokenKeymapRecord()
{
    skip_if_rpm_testing_off && return
    check_dirindex_broken_record '_`'
}

# an index made with --mo=nodesc keeps no package info: ls --qf shows (none)
# for the summary, desc -L no changelog
testIndexWithoutPackageInfo()
{
    skip_if_rpm_testing_off && return

    build a
    $RAW_POLDEK --st dir -s $REPO --mkidx --mo=nodesc || fail "mkidx failed"

    out=$($POLDEK ls --qf '%{NAME}:%{SUMMARY}\n' a)
    assertEquals "ls --qf failed ($out)" "$?" "0"
    echo "$out" | grep -qx 'a:(none)'
    assertEquals "no a:(none) line ($out)" "$?" "0"

    out=$($POLDEK desc -L a)
    assertEquals "desc -L failed ($out)" "$?" "0"
}

# an alias that replaces another one is what its own line makes it: with
# parameters, of the shell only (an external command) or neither
testAliasRedefined()
{
    skip_if_rpm_testing_off && return

    build a
    index

    # only an alias of the system's cli.conf can be replaced. Does the poldek
    # under test have "ll = ls -l" and a less of the shell only there? The
    # list shows the first; an alias to less is found, and not listed
    mkdir -p $TMPDIR/probe
    printf '[aliases]\nprobe = less\n' > $TMPDIR/probe/.poclidekrc
    out=$(HOME=$TMPDIR/probe $POLDEK -q --cmd alias 2>&1)
    if ! echo "$out" | grep -q '^ll  *= ls -l$' ||
       echo "$out" | grep -q -e 'could not determine aliased command' -e '^less ' -e '^probe '; then
        startSkipping
        fail # to count skipping tests
        endSkipping
        return
    fi

    mkdir -p $TMPDIR/home
    printf '[aliases]\nll = ls -q %%1*\nless = ls -q\n' > $TMPDIR/home/.poclidekrc

    local listed=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'ls -q a' 2>&1)

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'll a' 2>&1)
    assertEquals "ll a ($out)" "$listed" "$out"

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'less a' 2>&1)
    assertEquals "less a ($out)" "$listed" "$out"
}

# an alias with a parameter passes its argument whole, a long one too
testAliasParameterLongArgument()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\np1 = ls %%1\n' > $TMPDIR/home/.poclidekrc
    arg=$(printf 'x%.0s' $(seq 1 2000))

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd "p1 $arg" 2>&1)
    got=$(echo "$out" | cut -c1-80)
    assertEquals "ls did not get the argument ($got)" \
                 "error: $arg: no such package or directory" "$out"
}

# an alias that leads back to itself is refused, not expanded without end,
# also when the way back goes through an alias with a parameter
testAliasLoop()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nself = self a\nloopa = loopb\nloopb = loopa\nrun = %%1\nrl = run rl\n' \
           > $TMPDIR/home/.poclidekrc

    for alias in self loopa rl; do
        out=$(HOME=$TMPDIR/home $POLDEK -q --cmd "$alias" 2>&1)
        assertEquals "$alias: exit code ($out)" "1" "$?"
        echo "$out" | grep -qx "error: $alias: alias refers to itself"
        assertEquals "$alias: no loop error ($out)" "0" "$?"
    done
}

# the aliases of the cli.conf that is installed name options their commands have
testShippedAliases()
{
    mkdir -p $TMPDIR/home
    cp ../conf/cli.conf $TMPDIR/home/.poclidekrc

    # those that run an external command have no help
    local aliases=$(sed -n '/^\[aliases\]/,$p' ../conf/cli.conf |
                    sed -n '/= *!/d; s/^\([a-zA-Z][^ =]*\) *=.*/\1/p')
    assertNotNull "no aliases read from ../conf/cli.conf" "$aliases"

    for alias in $aliases; do
        out=$(HOME=$TMPDIR/home $POLDEK_NOCONF -q --cmd "$alias --help" 2>&1)
        assertEquals "$alias --help: exit code ($out)" "0" "$?"
        echo "$out" | grep -q -e 'invalid option' -e 'unrecognized option' -e 'no such command'
        assertEquals "$alias --help ($out)" "1" "$?"
    done
}

# an alias may use another alias more than once
testAliasUsedTwice()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nla = ls a\ntwice = la; la\n' > $TMPDIR/home/.poclidekrc

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd "twice" 2>&1)
    assertEquals "twice failed ($out)" "0" "$?"
    n=$(echo "$out" | grep -c '^a-1-1')
    assertEquals "a-1-1 not listed twice ($out)" "2" "$n"
}

# an alias may come back in its own expansion through an argument
testAliasBackThroughArgument()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nrun = %%1\n' > $TMPDIR/home/.poclidekrc

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd "run run ls" 2>&1)
    assertEquals "run run ls failed ($out)" "0" "$?"
    echo "$out" | grep -q '^a-1-1'
    assertEquals "a-1-1 not listed ($out)" "0" "$?"
}

# a quoted argument may begin with | or ;
testCmdQuotedPipeOrSemicolon()
{
    skip_if_rpm_testing_off && return

    build a
    build abc
    index

    out=$($POLDEK --cmd "search --perlre '|^a\$|' | install" 2>&1)
    assertEquals "search | install failed ($out)" "0" "$?"
    rpm_state_check "a" "abc"

    out=$($POLDEK --cmd "search --perlre ';^abc\$;'" 2>&1)
    assertEquals "search failed ($out)" "0" "$?"
    echo "$out" | grep -q '^abc-1-1'
    assertEquals "abc-1-1 not found ($out)" "0" "$?"
}

# each command of a line starts with the settings poldek was given: neither
# the packages nor the options of the command before it are its own
testCmdsOfLineShareNothing()
{
    skip_if_rpm_testing_off && return

    local out

    build a
    build b
    build c
    build y -r nosuchcap
    index

    out=$($POLDEK -q --cmd "ls -q a ; ls -q b ; ls -q c" 2>&1)
    assertEquals "ls ; ls ; ls" "a-1-1 b-1-1 c-1-1" "$(echo "$out" | grep -o '^[abc]-1-1' | xargs)"

    out=$($POLDEK -q ls -q a ";" ls -q b 2>&1)
    assertEquals "ls ; ls as arguments" "a-1-1 b-1-1" "$(echo "$out" | grep -o '^[abc]-1-1' | xargs)"

    out=$($POLDEK -q --cmd "ls -q a ; ls -q b | desc" 2>&1)
    assertEquals "ls ; ls | desc" "b-1-1" "$(echo "$out" | grep '^Package:' | grep -o '[ab]-1-1' | xargs)"

    # --test of the first is not the second's
    out=$($POLDEK --cmd "install --test a ; install b" 2>&1)
    rpm_state_check "b" "a"

    # nor is --nodeps
    out=$($POLDEK --cmd "install --nodeps c ; install y" 2>&1)
    rpm_state_check "b,c" "y"

    # an option of poldek is every command's
    out=$($POLDEK --test --cmd "install a ; uninstall b" 2>&1)
    rpm_state_check "b,c" "a"
}

# -q of a command does not quieten the commands after it
testCmdQuietOnlyForItself()
{
    skip_if_rpm_testing_off && return

    local out

    build a
    build b
    index

    out=$($POLDEK --cmd "install -q --test a ; install --test b" 2>&1)
    echo "$out" | grep -q 'There are 1 package to install'
    assertEquals "install after install -q said nothing ($out)" "0" "$?"

    out=$($POLDEK --cmd "ls -q a | install --test" 2>&1)
    echo "$out" | grep -q 'There are 1 package to install'
    assertEquals "install after ls -q | said nothing ($out)" "0" "$?"
}

# a pipeline in the middle of a line: its commands run on transactions of
# their own, so its packages are not the next command's
testCmdPipelineInTheMiddle()
{
    skip_if_rpm_testing_off && return

    local out

    build a
    build b
    index

    out=$($POLDEK -q --cmd "ls -q a | desc ; ls -q b" 2>&1)
    assertEquals "ls | desc ; ls" "b-1-1" \
        "$(echo "$out" | grep -o '^[ab]-1-1' | xargs)"
    assertEquals "ls | desc ; ls, what desc described" "a-1-1" \
        "$(echo "$out" | grep '^Package:' | grep -o '[ab]-1-1' | xargs)"

    out=$($POLDEK -q --cmd "ls -q a | install --test ; ls -q b" 2>&1)
    assertEquals "ls | install ; ls" "b-1-1" \
        "$(echo "$out" | grep -o '^[ab]-1-1' | xargs)"
}

# runs $1 as --cmd through rcmd (tests/rcmd_user.c), on a transaction with
# the mask $2 if given; what it prints in $out
rcmd_line() {
    out=$(env ${2:+RCMD_MASK=$2} LD_PRELOAD=$PWD/.libs/rcmd_user.so \
              $POLDEK -q --cmd "$1" 2>&1)
}

# the packages of $out the line left in the caller's pipe
rcmd_packages() {
    echo "$out" | sed -n 's/^rcmd package: \([abc]-1-1\).*/\1/p' | xargs
}

# the packages desc described into the caller's pipe
rcmd_described() {
    echo "$out" | grep '^rcmd output: Package:' | grep -o '[abc]-1-1' | xargs
}

# the arguments the caller's transaction is left with
rcmd_arguments() {
    echo "$out" | sed -n 's/^rcmd argument: //p' | xargs
}

# a line run through rcmd on the caller's transaction: what the last command
# of the line gives goes to the caller, also when it is the right side of a
# pipe, and nothing of the commands before it; the packages the caller gave
# go to every command, and the transaction is left with the last one's
testCmdLineThroughRcmd()
{
    skip_if_rpm_testing_off && return

    local out

    build a
    build b
    build c
    index

    rcmd_line "ls -q a ; ls -q b"
    assertEquals "ls ; ls, packages ($out)" "b-1-1" "$(rcmd_packages)"

    rcmd_line "ls -q a ; search -q b | ls -q"
    assertEquals "ls ; search | ls, packages ($out)" "b-1-1" "$(rcmd_packages)"

    rcmd_line "ls -q a ; ls -q b | desc"
    assertEquals "ls ; ls | desc, described ($out)" "b-1-1" "$(rcmd_described)"

    rcmd_line "ls -q a | desc ; ls -q b"
    assertEquals "ls | desc ; ls, packages ($out)" "b-1-1" "$(rcmd_packages)"
    assertEquals "ls | desc ; ls, described ($out)" "" "$(rcmd_described)"

    rcmd_line "ls -q b ; ls -q c" a
    assertEquals "mask a, ls b ; ls c, the first ($out)" "a-1-1 b-1-1" \
        "$(echo "$out" | grep -o '^[abc]-1-1' | xargs)"
    assertEquals "mask a, ls b ; ls c, packages ($out)" "a-1-1 c-1-1" \
        "$(rcmd_packages)"
    assertEquals "mask a, ls b ; ls c, arguments left ($out)" "a c" \
        "$(rcmd_arguments)"
}

# in multilib mode, where package ids end in .ARCH, ls still finds a
# package by name-version-release
testLsNvrMultilib()
{
    skip_if_rpm_testing_off && return

    build a 1-1
    index

    out=$($POLDEK -Omultilib=1 ls a-1-1 2>&1)
    assertEquals "ls a-1-1 failed ($out)" "$?" "0"
    echo "$out" | grep -q '^a-1-1'
    assertEquals "a-1-1 not listed ($out)" "$?" "0"
}

# a full package id wins over name-version-release: "m-1-1.i686" lists
# the i686 package, not also m-1-1.i686.x86_64 (release "1.i686")
testLsExplicitArchOverNvrMultilib()
{
    skip_if_rpm_testing_off && return

    build m 1-1 -a i686 -f /m.i686
    build m 1-1.i686 -a x86_64 -f /m.x86_64
    index

    out=$($POLDEK -Omultilib=1 ls m-1-1.i686 2>&1)
    assertEquals "ls m-1-1.i686 failed ($out)" "$?" "0"
    n=$(echo "$out" | grep -c '^m-1-1')
    assertEquals "m-1-1.i686 should list one package ($out)" "1" "$n"
}

# a command given as arguments: the first one is parsed as a line (so it may
# hold the command with its options, or all the commands), each of the others
# is one word, whatever it holds; a lone | or ; parts commands, and the
# argument after it is parsed as a line again
testCmdArgumentsAreWords()
{
    skip_if_rpm_testing_off && return

    local shown="grep -o ^[ab]*-1-1"

    build a
    build ab
    build b
    index

    out=$($POLDEK ls -q 'a b' 2>&1)
    echo "$out" | grep -q 'a b: no such package'
    assertEquals "'a b' is not one argument ($out)" "0" "$?"
    assertEquals "'a b' listed packages ($out)" "" "$(echo "$out" | $shown)"

    out=$($POLDEK ls -q 'a;b' 'a|b' 2>&1)
    assertEquals "'a;b' or 'a|b' is not one argument ($out)" "2" \
        "$(echo "$out" | grep -c -e 'a;b: no such package' -e 'a|b: no such package')"

    out=$($POLDEK search --perlre '|^ab|' 2>&1)
    assertEquals "search --perlre '|^ab|' failed ($out)" "0" "$?"
    assertEquals "ab-1-1 not found ($out)" "ab-1-1" "$(echo "$out" | $shown)"

    # an alias gets the words as they are
    out=$($POLDEK upgrade --test 'a b' 2>&1)
    echo "$out" | grep -q 'a b: no such package'
    assertEquals "the alias did not get 'a b' as one argument ($out)" "0" "$?"

    out=$($POLDEK 'ls -q' a 2>&1)
    assertEquals "'ls -q' a ($out)" "a-1-1" "$(echo "$out" | $shown | xargs)"

    out=$($POLDEK 'ls -q a' 'a b' 2>&1)
    echo "$out" | grep -q 'a b: no such package'
    assertEquals "'ls -q a' 'a b' ($out)" "0" "$?"

    out=$($POLDEK "search -p 'a*' | ls -q" 2>&1)
    assertEquals "a line with a pipe ($out)" "a-1-1 ab-1-1" "$(echo "$out" | $shown | xargs)"

    out=$($POLDEK search -p 'a*' '|' ls -q 2>&1)
    assertEquals "a lone | ($out)" "a-1-1 ab-1-1" "$(echo "$out" | $shown | xargs)"

    out=$($POLDEK search -p a ';' 'search -p' b 2>&1)
    assertEquals "a lone ; ($out)" "a-1-1 b-1-1" "$(echo "$out" | $shown | xargs)"

    out=$($POLDEK ls -q a '' 2>&1)
    assertEquals "an empty argument ($out)" "a-1-1" "$(echo "$out" | $shown | xargs)"
}

# !command runs an external command where a command stands, which the shell
# only allows: as an argument a word that begins with ! is a word
testExternalCommandOnlyAsCommand()
{
    skip_if_rpm_testing_off && return

    build a
    index

    out=$($POLDEK ls -q '!a' 2>&1)
    echo "$out" | grep -q '!a: no such package'
    assertEquals "ls did not get !a as an argument ($out)" "0" "$?"

    out=$($POLDEK --cmd "ls -q '!a'" 2>&1)
    echo "$out" | grep -q '!a: no such package'
    assertEquals "ls of a line did not get !a as an argument ($out)" "0" "$?"

    out=$(printf '!echo first\nls -q a; !echo second\n!echo !third\nls -q !a\nquit\n' |
          timeout 60 script -qec "$POLDEK --noask --shell" /dev/null |
          tr -d '\r' | sed 's/\x1b\[[0-9;?]*[A-Za-z]//g')
    # the shell is not in every build
    echo "$out" | grep -q 'built without interactive mode' && return
    assertEquals "!echo as a command ($out)" "1" "$(echo "$out" | grep -cx first)"
    assertEquals "!echo after ; ($out)" "1" "$(echo "$out" | grep -cx second)"
    assertEquals "!echo did not get !third as an argument ($out)" "1" "$(echo "$out" | grep -cx '!third')"
    echo "$out" | grep -q '!a: no such package'
    assertEquals "ls in the shell did not get !a as an argument ($out)" "0" "$?"
}

# TAB after "--" in the shell completes the options of the command the
# line's first word leads to, and offers none where there is no such command
testShellOptionCompletion()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nla = ls a\npla = la\nself = self a\nrun = %%1\nvia = sear\ntwice = via\nzza = ls\nzzb = ls\namb = zz\nchain = ls -q a ; search\ntabbed = search\t-p\npipecase = ls -q a | des\np1 = ls -q %%1\nearg = search %%1 a ; ls -q a\n' \
           > $TMPDIR/home/.poclidekrc

    # what the shell shows when $1 (a printf format) is typed at its prompt:
    # typed earlier, it would be the terminal that reads the control characters
    shell() {
        local in=$TMPDIR/shell.in out=$TMPDIR/shell.out i=0

        rm -f $in $out
        mkfifo $in
        HOME=$TMPDIR/home timeout 60 script -qec "$POLDEK --noask --shell" /dev/null \
            < $in > $out 2>&1 &
        exec 9> $in
        while ! grep -q -e 'poldek:' -e 'built without interactive mode' $out && [ $i -lt 300 ]; do
            sleep 0.1
            i=$((i + 1))
        done
        printf "$1" >&9
        exec 9>&-
        wait
        tr -d '\r' < $out | sed 's/\x1b\[[0-9;?]*[A-Za-z]//g'
    }

    out=$(shell 'quit\n')
    # the shell is not in every build
    if echo "$out" | grep -q 'built without interactive mode'; then
        startSkipping
        fail # to count skipping tests
        endSkipping
        return
    fi

    # a command, an alias, an alias of an alias; spaces before the command;
    # an alias that puts its argument into its one command
    local line
    for line in 'ls --rev' 'la --rev' 'pla --rev' '  ls --rev' 'p1 --rev'; do
        out=$(shell "$line"'\t\nquit\n')
        echo "$out" | grep -q -- "$line"'erse'
        assertEquals "<$line>: --reverse not completed ($out)" "0" "$?"
    done

    # an alias to a command by the beginning of its name, as a line runs
    # it; the command itself so; an alias of several commands, whose last
    # one gets the options; a tab in an alias's line; a tab (typed after ^V)
    # after the command
    for line in 'via --summ' 'twice --summ' 'sear --summ' 'chain --summ' 'tabbed --summ'; do
        out=$(shell "$line"'\t\nquit\n')
        echo "$out" | grep -q -- "$line"'ary'
        assertEquals "<$line>: --summary not completed ($out)" "0" "$?"
    done

    # a pipe, whose last command is named by the beginning of its name
    out=$(shell 'pipecase --confl\t\nquit\n')
    echo "$out" | grep -q -- 'pipecase --conflicts'
    assertEquals "<pipecase --confl>: --conflicts not completed ($out)" "0" "$?"

    out=$(shell 'ls\026\t--rev\t\nquit\n')
    echo "$out" | grep -q -- '--reverse'
    assertEquals "ls, a tab, --rev: --reverse not completed ($out)" "0" "$?"

    # nothing to offer: an alias to itself, to its argument, a command
    # without options, no command at all, the beginning of several names (as
    # an alias's line and typed), a word longer than any command, an option
    # of an alias's command that is not its last, an alias of several
    # commands that puts its argument into one of them
    local long=$(printf 'x%.0s' $(seq 1 70))
    for line in 'self --rev' 'run --rev' 'alias --rev' 'nosuch --rev' 'amb --rev' 'zz --rev' \
                "$long --rev" 'chain --rev' 'earg --rev' 'earg --summ'; do
        out=$(shell "$line"'\t\t\n!echo alive\nquit\n')
        assertEquals "<$line> and TAB: the shell did not go on ($out)" \
                     "1" "$(echo "$out" | grep -cx alive)"
        echo "$out" | grep -q -e '--reverse' -e '--summary'
        assertEquals "<$line>: an option offered ($out)" "1" "$?"
    done
}

# the arguments an alias does not use for its parameters go after its
# line as the words they are
testAliasPassesArgumentsAsWords()
{
    skip_if_rpm_testing_off && return

    build a
    build ab
    build b
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nplainls = ls -q\np1 = ls -q %%1\nrun = %%1\n' > $TMPDIR/home/.poclidekrc

    out=$(HOME=$TMPDIR/home $POLDEK plainls "a'b" 'a|b' 2>&1)
    assertEquals "plainls did not get a'b and a|b ($out)" "2" \
        "$(echo "$out" | grep -c -e "a'b: no such package" -e 'a|b: no such package')"

    out=$(HOME=$TMPDIR/home $POLDEK --cmd "plainls 'a b'" 2>&1)
    echo "$out" | grep -q 'a b: no such package'
    assertEquals "plainls of a line did not get 'a b' ($out)" "0" "$?"

    # with a parameter used, the rest follow the line with it put in
    out=$(HOME=$TMPDIR/home $POLDEK --cmd 'p1 a b' 2>&1)
    assertEquals "p1 a b ($out)" "a-1-1 b-1-1" "$(echo "$out" | grep -o '^[ab]*-1-1' | xargs)"

    out=$(HOME=$TMPDIR/home $POLDEK --cmd 'run ls -q a' 2>&1)
    assertEquals "run ls -q a ($out)" "a-1-1" "$(echo "$out" | grep -o '^[ab]*-1-1' | xargs)"
}

# the argument put in for an alias's %N stays within the word that names
# it, whatever it contains: it is not parsed as a part of the alias's line
testAliasParameterIsOneWord()
{
    skip_if_rpm_testing_off && return

    build a
    build ab
    build b
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\np1 = ls -q %%1\nglob = ls -q %%1*\nnm = ls -q %%1 %%0\nsuffix = ls -q "%%1"b\ndigit = ls -q "%%1"2\n' \
           > $TMPDIR/home/.poclidekrc

    local arg
    for arg in 'a b' 'a|b' 'a;b' 'a ; ls -q b' "a'b" 'a"b' 'a%b'; do
        out=$(HOME=$TMPDIR/home $POLDEK -q p1 "$arg" 2>&1)
        assertEquals "p1 with <$arg> as a word ($out)" \
                     "error: $arg: no such package or directory" "$out"
    done

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd "p1 'a b'" 2>&1)
    assertEquals "p1 'a b' of a line ($out)" \
                 "error: a b: no such package or directory" "$out"

    # within a word
    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'glob a' 2>&1)
    assertEquals "glob a ($out)" "a-1-1 ab-1-1" "$(echo "$out" | grep -o '^[ab]*-1-1' | xargs)"

    out=$(HOME=$TMPDIR/home $POLDEK -q glob 'a b' 2>&1)
    assertEquals "glob with <a b> ($out)" "error: a b*: no such package or directory" "$out"

    # a quote of the alias's line ends the parameter's number
    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'suffix a' 2>&1)
    assertEquals "suffix a ($out)" \
                 "$(HOME=$TMPDIR/home $POLDEK -q --cmd 'ls -q ab' 2>&1)" "$out"

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'digit a' 2>&1)
    assertEquals "digit a ($out)" "error: a2: no such package or directory" "$out"

    # the arguments left follow, also when the alias uses its own name
    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'nm a b' 2>&1)
    assertEquals "nm a b ($out)" "a-1-1 b-1-1" "$(echo "$out" | grep -o '^[ab]*-1-1' | xargs)"

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'p1' 2>&1)
    assertEquals "p1 without an argument ($out)" \
                 "error: p1: apply arguments failed (not enough arguments?)" "$out"
}

# a % of an alias's line that names no argument's number is left as written
testAliasLiteralPercent()
{
    skip_if_rpm_testing_off && return

    build a
    index

    mkdir -p $TMPDIR/home
    printf '[aliases]\nlit = ls -q %%{NAME} 100%%x\nlitp = ls -q %%{NAME} %%1\nbad = ls -q %%1x\n' \
           > $TMPDIR/home/.poclidekrc

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'lit a' 2>&1)
    assertEquals "lit a ($out)" "2" \
        "$(echo "$out" | grep -c -e '^error: %{NAME}: no such package' -e '^error: 100%x: no such package')"
    echo "$out" | grep -q '^a-1-1'
    assertEquals "lit did not pass a on ($out)" "0" "$?"

    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'litp a' 2>&1)
    echo "$out" | grep -q '^error: %{NAME}: no such package' && echo "$out" | grep -q '^a-1-1'
    assertEquals "litp a ($out)" "0" "$?"

    # a number followed by letters is a mistyped parameter
    out=$(HOME=$TMPDIR/home $POLDEK -q --cmd 'bad a' 2>&1)
    assertEquals "bad a ($out)" \
                 "error: bad: apply arguments failed (not enough arguments?)" "$out"
}

# search fails when its pattern does not compile
testSearchInvalidPattern()
{
    skip_if_rpm_testing_off && return

    build a
    index

    out=$($POLDEK search --perlre '/(/' 2>&1)
    rc=$?
    assertTrue "search with an invalid pattern succeeded ($out)" "[ $rc -ne 0 ]"

    out=$($POLDEK search --perlre '/^a$/' 2>&1)
    assertEquals "search failed ($out)" "0" "$?"
    echo "$out" | grep -q '^a-1-1'
    assertEquals "a-1-1 not found ($out)" "0" "$?"
}

# search over a directory without packages, such as the available
# packages of an empty source, matches nothing; -p looks only at the
# capabilities, the default fields also at summaries and descriptions
testSearchNoPackages()
{
    skip_if_rpm_testing_off && return

    mkdir -p $TMPDIR/empty
    for opt in -p ""; do
        out=$($RAW_POLDEK --st dir -s $TMPDIR/empty --skip-installed search $opt a 2>&1)
        assertEquals "search${opt:+ $opt} a failed ($out)" "0" "$?"
        echo "$out" | grep -q "No package matches 'a'"
        assertEquals "search${opt:+ $opt} a: no 'No package matches' ($out)" "0" "$?"
    done
}

testUpgrade()
{
    skip_if_rpm_testing_off && return

    build a -v 2
    build a-libs -v 2
    index

    build_installed a
    build_installed a-libs

    n=$($POLDEK ls -u | grep -E '^(a|a-libs)' | wc -l)
    assertEquals "expected 2 packages to be upgradeable, got $n" "$n" "2"

    msg $POLDEK install -F -v a~
    $POLDEK install -F -v a~

    #$RPM -ev a --justdb
    #$RPM -ev a-libs --justdb
    #$RPM -qa

    rpm_state_check "a-2,a-libs-2" "a-1,a-libs-1"
}

# desc -B lists a package whose requirement the described version satisfies,
# not any requirer of its name
testDescRequiredByVersion()
{
    skip_if_rpm_testing_off && return

    build x 1-1
    build x 2-1
    build y 1-1 -r "'x < 2'"
    build z 1-1 -r "'x >= 2'"
    build w 1-1 -r x
    build py27 2.7.18-1 -p "'python(abi) = 2.7'"
    build py3 3.13.1-1 -p "'python(abi) = 3.13'"
    build d 1-1 -r "'python(abi) = 2.7'"
    build e 1-1 -r "'python(abi) = 3.13'"
    # as in the dependency solver, a capability without a version
    # does not satisfy a versioned requirement
    build u 1-1 -p foo
    build r 1-1 -r "'foo >= 2'"
    build s 1-1 -r foo
    index

    for t in "x-1-1:w, y" "x-2-1:w, z" "py27-2.7.18-1:d" "py3-3.13.1-1:e" "u-1-1:s"; do
        p=${t%%:*}
        out=$($POLDEK desc -B $p.noarch)
        assertEquals "desc $p failed" "$?" "0"
        reqby=$(echo "$out" | sed -n 's/^Required(by): *//p')
        assertEquals "$p required by" "${t#*:}" "$reqby"
    done
}

testUninstall()
{
    skip_if_rpm_testing_off && return

    build a
    index

    build_installed a
    build_installed b
    build_installed a-libs

    msg $POLDEK uninstall -y a~
    $POLDEK uninstall -y a~

    #$RPM -ev a --justdb
    #$RPM -ev a-libs --justdb
    #$RPM -qa

    rpm_state_check "b" "a,a-libs"
}

# "use sudo" is for ordinary users: root removes packages with rpm itself,
# as it installs them
testUninstallAsRootWithoutSudo()
{
    skip_if_rpm_testing_off && return
    if ! is_root; then          # the tests use sudo as an ordinary user
        startSkipping
        fail
        endSkipping
        return
    fi

    build a
    index

    build_installed a
    build_installed b

    # a sudo that refuses, so removing through it fails
    local sudo="$TMPDIR/sudo" sudo_log="$TMPDIR/sudo.log"
    printf '#!/bin/sh\necho "$*" >> %s\nexit 1\n' "$sudo_log" > $sudo
    chmod 755 $sudo
    rm -f $sudo_log

    $POLDEK -Ouse_sudo=y -Osudo_command=$sudo uninstall -y a

    assertFalse "sudo was run: $(cat $sudo_log 2>/dev/null)" "[ -s $sudo_log ]"
    rpm_state_check "b" "a"
}

# without repositories desc runs in /installed: -R and -B look among the
# installed packages
testDescInstalled()
{
    skip_if_rpm_testing_off && return

    build_installed b
    build_installed a -r b
    build_installed c -r a

    msg $RAW_POLDEK --root $DESTINATION_REPO desc -R -B a
    out=$($RAW_POLDEK --root $DESTINATION_REPO desc -R -B a)
    assertEquals "desc failed" "$?" "0"
    echo "$out" | grep -qE '^Required\(pkgs\): +sh, b$'
    assertEquals "a should require b" "$?" "0"
    echo "$out" | grep -qE '^Required\(by\): +c$'
    assertEquals "a should be required by c" "$?" "0"
}

# -R finds the owners of a required file and directory also when the
# installed packages come from the cache
testDescInstalledPathsFromCache()
{
    skip_if_rpm_testing_off && return

    build_installed f -f /usr/bin/zzf
    build_installed d -fd /usr/share/zzd/sub
    build_installed a -r /usr/bin/zzf -r /usr/share/zzd/sub
    # older than the cache made below, which then counts as current
    touch -d '-1 hour' $DESTINATION_REPO$($RPM --eval %_dbpath)/*

    for src in rpmdb rpmdbcache; do
        out=$($RAW_POLDEK --root $DESTINATION_REPO desc -R a)
        echo "$out" | grep -q "^Loading \[$src\]"
        assertEquals "installed packages not loaded from $src" "$?" "0"

        req=$(echo "$out" | grep '^Required(pkgs):')
        for p in d f; do
            echo "$req" | grep -qE "[ ,]$p(,|$)"
            assertEquals "$src: a should require $p ($req)" "$?" "0"
        done
    done
}

# and right after an install in the shell, with the installed packages
# read from the cache before it
testDescInstalledAfterInstall()
{
    skip_if_rpm_testing_off && return

    build_installed f -f /opt/zzf/tool
    build a -r /opt/zzf/tool
    index
    touch -d '-1 hour' $DESTINATION_REPO$($RPM --eval %_dbpath)/*
    $RAW_POLDEK --root $DESTINATION_REPO --cmd ls >/dev/null  # makes the cache

    out=$(printf 'cd /installed\nls\ncd /all-avail\ninstall --justdb a\ncd /installed\ndesc -R a\nquit\n' |
          timeout 60 script -qec "$POLDEK --noask --shell" /dev/null |
          tr -d '\r' | sed 's/\x1b\[[0-9;?]*[A-Za-z]//g')
    echo "$out" | grep -q "Loading \[rpmdbcache\]"
    assertEquals "installed packages not loaded from the cache" "$?" "0"

    req=$(echo "$out" | grep 'Required(pkgs):')
    echo "$req" | grep -qE "[ ,]f(,|$)"
    assertEquals "a should require f ($req)" "$?" "0"
}

testClean()
{
    skip_if_rpm_testing_off && return

    typeset n=$(find $CACHEDIR | wc -l)
    assertEquals "$CACHEDIR should be empty" "$n" "1"

    cachedir_clean
    mkdir -p $CACHEDIR/foo/bar/baz
    touch $CACHEDIR/foo/foo.txt
    touch $CACHEDIR/foo/bar/bar.txt
    touch $CACHEDIR/foo/bar/baz/bar.txt
    mkfifo $CACHEDIR/fifo

    typeset OUTSIDEDIR="$CACHEDIR/../"
    touch $CACHEDIR/../existing-file

    ln -s ../existing-file $CACHEDIR/symlink
    ln -s ../non-existing $CACHEDIR/broken-symlink
    #ls -l $CACHEDIR/
    n=$(find $CACHEDIR | wc -l)
    #find $CACHEDIR | nl
    if [ "$n" -lt 8 ]; then
        find $CACHEDIR | nl
        fail "$CACHEDIR should contain at least 8 items"
    fi

    $RAW_POLDEK clean
    n=$(find $CACHEDIR | wc -l)
    [ "$n" != "1" ] && find $CACHEDIR
    assertEquals "$CACHEDIR should be empty after clean" "$n" "1"

    test -f $CACHEDIR/../existing-file || fail "$CACHEDIR/../existing-file should still be there"

}

# the source given with -s has no name, so up REPO cannot match it: the
# selection skips it (a NULL name never reaches strcmp()) and reports the
# name it found no source for
testUpRepoSkipsSourceWithoutName()
{
    skip_if_rpm_testing_off && return

    index
    before=$(find $CACHEDIR | sort)
    out=$($POLDEK up nosuch 2>&1)
    rc=$?
    [ "$rc" -ne 0 ] || fail "up nosuch succeeded: $out"
    echo "$out" | grep -q 'no such source' || \
        fail "no error for an unknown source: $out"
    assertEquals "up nosuch updated the source given with -s" "$before" "$(find $CACHEDIR | sort)"
}

# a source given as a bare path (-s PATH) has no name: the source part
# of a hold or ignore mask matches it as an empty name
testIgnoreSourceMaskWithoutName()
{
    skip_if_rpm_testing_off && return

    build a
    build b
    index

    out=$($POLDEK --ignore '(null):*' ls 2>&1)
    assertEquals "ls failed ($out)" "0" "$?"
    assertEquals "'(null):*' ignored packages ($out)" "2" "$(echo "$out" | grep -c '^[ab]-1-1')"

    out=$($POLDEK --ignore '*:a*' ls 2>&1)
    assertEquals "ls failed ($out)" "0" "$?"
    assertEquals "'*:a*' did not ignore only a ($out)" "b-1-1" "$(echo "$out" | grep -o '^[ab]-1-1')"
}

# a mask is matched with the whole name-version-release of a package, however
# long the name of its source is
testIgnoreMaskLongSourceName()
{
    skip_if_rpm_testing_off && return

    local conf="$TMPDIR/source-ignore.conf" name type out

    build a
    build b
    index

    name=$(printf 's%.0s' $(seq 1 507))
    for type in pndir dir; do
        printf '[source]\nname = %s\ntype = %s\npath = %s/\nignore = a-1-1\n' $name $type $REPO > $conf
        rm -rf $CACHEDIR
        out=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n $name --cmd ls 2>&1)
        assertEquals "$type: ignore = a-1-1 ($out)" "b-1-1" "$(echo "$out" | grep -o '^[ab]-1-1' | xargs)"

        printf '[source]\nname = %s\ntype = %s\npath = %s/\nignore = a-1\n' $name $type $REPO > $conf
        rm -rf $CACHEDIR
        out=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n $name --cmd ls 2>&1)
        assertEquals "$type: ignore = a-1 ($out)" "a-1-1 b-1-1" "$(echo "$out" | grep -o '^[ab]-1-1' | xargs)"
    done

    printf '[source]\nname = %s\ntype = dir\npath = %s/\nignore = %s:b-1-1.noarch\n' $name $REPO $name > $conf
    rm -rf $CACHEDIR
    out=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n $name --cmd ls 2>&1)
    assertEquals "dir: ignore = NAME:b-1-1.noarch ($out)" "a-1-1" "$(echo "$out" | grep -o '^[ab]-1-1' | xargs)"
}

# -vvv names each package the source ignores the same way, however it comes
# to be ignored: dropped after the load that writes the stub index, left out
# of the stub index as it is read, or skipped in the index by a later load
testSourceIgnoreVerbose()
{
    skip_if_rpm_testing_off && return

    local conf="$TMPDIR/source-ignore.conf" opt name out

    build a
    build b
    index
    touch -d '-1 hour' $REPO/packages.ndir.*    # for the stub index to stay current
    printf '[source]\nname = s\ntype = pndir\npath = %s/\nignore = a*\n' $REPO > $conf

    for opt in "" "-Omultilib=0"; do
        name="a-1-1.noarch"
        [ -n "$opt" ] && name="a-1-1"
        rm -rf $CACHEDIR

        # the second run reads the stub index, then loads the source for desc
        for cmd in ls "desc b"; do
            out=$($POLDEK_RAW $opt --conf $conf --cachedir $CACHEDIR -n s -vvv --cmd "$cmd" 2>&1)
            assertEquals "$cmd ignoring a failed, $opt ($out)" "0" "$?"
            echo "$out" | grep -q "^ *ignored $name$" ||
                fail "$cmd $opt: no 'ignored $name' ($out)"
            [ "$cmd" = ls ] || echo "$out" | grep -q 'Loading stub index' ||
                fail "$cmd $opt: the stub index was not read ($out)"
            assertEquals "$cmd $opt: a named another way ($out)" "" \
                "$(echo "$out" | grep 'ignored a-' | grep -v "^ *ignored $name$")"
        done
    done
}

# an ignore mask in a source section hides what it hides in [ global ],
# whatever the type of the source: a name, a name-version-release, one with
# the arch, a glob, each also after the name of the source
testSourceIgnoreMasks()
{
    skip_if_rpm_testing_off && return

    local conf="$TMPDIR/source-ignore.conf" type mask shown out rc

    build a
    build ab
    index

    for type in pndir dir; do
        for mask in a a-1-1 a-1-1.noarch 'a-[0-9]*' s:a 's:a-1*' other:a a.noarch; do
            shown="ab-1-1"
            case $mask in other:a | a.noarch) shown="a-1-1 ab-1-1" ;; esac

            printf '[source]\nname = s\ntype = %s\npath = %s/\nignore = %s\n' $type $REPO "$mask" > $conf
            rm -rf $CACHEDIR    # no stub index from the mask before
            out=$($POLDEK_RAW --conf $conf --cachedir $CACHEDIR -n s --cmd ls 2>&1)
            rc=$?
            assertEquals "ls of $type with ignore = $mask failed ($out)" "0" "$rc"
            assertEquals "$type: ignore = $mask ($out)" "$shown" \
                "$(echo "$out" | grep -o '^ab*-1-1' | xargs)"
        done
    done
}

# ls of a source: $1 its type, $2 the ignore line of its section, or none;
# the output in $out, the packages shown in $shown
ls_source()
{
    printf '[source]\nname = s\ntype = %s\npath = %s/\n%s\n' $1 $REPO "$2" > $TMPDIR/source-ignore.conf
    out=$($POLDEK_RAW --conf $TMPDIR/source-ignore.conf --cachedir $CACHEDIR -n s -vv --cmd ls 2>&1)
    shown=$(echo "$out" | grep -o '^[ab]-1-1' | xargs)
}

# ignore of a source hides the same packages with a cold cache and with a
# stub index in it, whatever masks were set when the stub index was written
testSourceIgnoreWithStubIndex()
{
    skip_if_rpm_testing_off && return

    local type out shown stub

    build a
    build b
    index
    for type in pndir dir; do
        # a stub index is current while it has the time of its source: of
        # the index or, with dir, of the directory
        touch -d '-1 hour' $REPO/packages.ndir.* $REPO
        rm -rf $CACHEDIR
        ls_source $type "ignore = a"
        assertEquals "$type: ignore = a, a cold cache ($out)" "b-1-1" "$shown"
        stub=$(find $CACHEDIR -name "stubindex.$type.zst")
        assertEquals "$type: packages in the stub index written with ignore = a" "2" \
            "$(zstdcat $stub | grep -vc "^%")"

        ls_source $type ""
        assertEquals "$type: no mask after ignore = a ($out)" "a-1-1 b-1-1" "$shown"
        echo "$out" | grep -q 'Loading \[' && fail "$type: the source was loaded, not its stub index ($out)"

        ls_source $type "ignore = a"
        assertEquals "$type: ignore = a, a warm cache ($out)" "b-1-1" "$shown"
        echo "$out" | grep -q 'Loading \[' && fail "$type: the source was loaded, not its stub index ($out)"

        ls_source $type "ignore = s:a"
        assertEquals "$type: ignore = s:a, a warm cache ($out)" "b-1-1" "$shown"
        echo "$out" | grep -q 'Loading \[' && fail "$type: the source was loaded, not its stub index ($out)"

        ls_source $type ""
        assertEquals "$type: no mask, a warm cache ($out)" "a-1-1 b-1-1" "$shown"
        echo "$out" | grep -q 'Loading \[' && fail "$type: the source was loaded, not its stub index ($out)"

        # a stub index of a version that wrote it without the ignored packages
        zstdcat $stub | grep -v -e '^%' -e '^a#' | zstd -q -c > $stub.old
        touch -r $stub $stub.old
        mv -f $stub.old $stub
        ls_source $type ""
        assertEquals "$type: no mask, a stub index without a left ($out)" "a-1-1 b-1-1" "$shown"
        assertEquals "$type: the stub index was not written again" "%stubindex v2" "$(zstdcat $stub | head -1)"

        # one of another version of the format
        zstdcat $stub | sed -e '1s/.*/%stubindex v3/' -e '/^a#/d' | zstd -q -c > $stub.old
        touch -r $stub $stub.old
        mv -f $stub.old $stub
        ls_source $type ""
        assertEquals "$type: no mask, a stub index of v3 without a ($out)" "a-1-1 b-1-1" "$shown"
        assertEquals "$type: the stub index of v3 was not written again" "%stubindex v2" "$(zstdcat $stub | head -1)"
    done
}

# what the cache of installed packages leaves out (descriptions, file lists)
# comes from the --root database, not from the host's
testDescInstalledRootFromCache()
{
    skip_if_rpm_testing_off && return

    build_installed a -f /usr/bin/zzroot
    # a cache made within a second of a database change counts as stale;
    # back-date the database so the cache made below counts as current
    $SUDO touch -d '-1 hour' $DESTINATION_REPO$($RPM --eval %_dbpath)/* || fail "back-dating the rpm database failed"

    for src in rpmdb rpmdbcache; do
        out=$($RAW_POLDEK --root $DESTINATION_REPO desc -d -f a)
        echo "$out" | grep -q "^Loading \[$src\]"
        assertEquals "installed packages not loaded from $src" "$?" "0"
        echo "$out" | grep -qE '^Summary: +a$'
        assertEquals "$src: no summary of a ($out)" "$?" "0"
        echo "$out" | grep -qE '^/usr/bin: +zzroot$'
        assertEquals "$src: no files of a ($out)" "$?" "0"
    done
}

# search --perlre takes /regexp/flags
testSearchPerlRegexp()
{
    skip_if_rpm_testing_off && return

    build a
    build abc
    index

    out=$($POLDEK search --perlre '/^A$/i' 2>&1)
    assertEquals "search failed ($out)" "0" "$?"
    echo "$out" | grep -q '^a-1-1'
    assertEquals "a-1-1 not found ($out)" "0" "$?"
    n=$(echo "$out" | grep -c '^abc-1-1')
    assertEquals "abc-1-1 found ($out)" "0" "$n"

    out=$($POLDEK search --perlre '/^A$/' 2>&1)
    n=$(echo "$out" | grep -c '^a-1-1')
    assertEquals "a-1-1 found without the i flag ($out)" "0" "$n"

    out=$($POLDEK search --perlre '/(/' 2>&1)
    echo "$out" | grep -q 'search: pattern: (:1: '
    assertEquals "no error for an invalid pattern ($out)" "0" "$?"
}


. ./sh/lib/shunit2
