#!/bin/sh
# $Id$

# --mkidx tests
. ./sh/lib/setup
. ./sh/lib/repo-setup
. ./sh/lib/compr-setup
. ./sh/lib/rpm-setup

setUp() {
    #repo_up
    sudo_up
}

# preloaded into poldek to make the close of a file fail
CLOSE_ERROR_SO="$PWD/.libs/close_error.so"

# the files of an index are replaced from a hidden .<name>.tmp.XXXXXX,
# which neither a finished nor a failed write may leave
assert_no_tmp() {
    local left=$(find $1 -name '.*.tmp.??????')
    [ -z "$left" ] || fail "temporary files left: $left"
}

# the checksums of the files of the index in $1
index_sums() {
    (cd $1 && find . -type f -name 'packages.*' ! -name '*.md5' | sort | xargs -r cksum)
}

# $1 with all the packages of $REPO but the last one, and an index of them
mkrepo_but_last() {
    rm -rf $1
    mkdir $1
    cp $REPO/*.rpm $1 || fail "cp failed"
    rm -f $1/$(basename $(ls $REPO/*.rpm | tail -1))
    $POLDEK_NOCONF -s $1 --mkidx || fail "mkidx failed"
}

#  Index creation use cases:
Case_a="-s /foo                   =>  dir  -> default type"
Case_b="--st type -s /foo         =>  type -> default type"
#Case_c="--st type /foo --mt dtype =>  type -> dtype" # irrelevant, as pndir is only creatable format
#Case_d="-s /foo --mt dtype        =>  dir  -> dtype" # irrelevant, as pndir is only creatable format
#Case_e="-s /foo --mt dtype,dtype2 =>  dir  -> dtype" # irrelevant, as pndir is only creatable format
Case_f="-n foo                    =>  dir (or original type) -> foo's type"
Case_g="-s /foo --mkidx=<path>    =>  index written outside the repo"
Case_h="-n foo --mkidx=<path>     =>  the same, with an explicit index name"


testCreateDefaultType()
{
    msgn $Case_a
    $POLDEK_NOCONF -s $REPO --mkidx || fail "mkidx #1 failed"
    die_if_empty_index "$REPO/packages.ndir$COMPR_EXT"

    $POLDEK_NOCONF -s $REPO --mkidx=$TMPDIR || fail "mkidx #2 failed"
    die_if_empty_index "$TMPDIR/packages.ndir$COMPR_EXT"
    if ! diff -u $REPO/packages.ndir.md $TMPDIR/packages.ndir.md; then
        fail "differ md's!"
    fi
}

#  b) --st dir -s /foo          =>  dir -> default type
testCreateFromDir()
{
    $POLDEK_NOCONF --st dir -s $REPO --index || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.ndir$COMPR_EXT"

    # move indexes to separate dir to make sure poldek will not faillback to load it as "dir" repo
    rm -rf $TMPDIR/tmprepo
    mkdir $TMPDIR/tmprepo
    mv $REPO/packages.ndir* $TMPDIR/tmprepo || fail "cp failed"

    check_repo_content $TMPDIR/tmprepo
}

# the descriptions (changelogs) are saved next to the index also when the path has a '%'
testCreateInDirWithPercent()
{
    local repo="$TMPDIR/re%20dpo"

    rm -rf $repo
    mkdir $repo
    cp $REPO/*.rpm $repo || fail "cp failed"

    $POLDEK_NOCONF --st dir -s $repo --index || fail "mkidx failed"
    die_if_empty_index "$repo/packages.ndir$COMPR_EXT"
    check_repo_content $repo
}

# --mkidx with the previous index takes no stack for each package of it,
# also with -vvv; with the stack limited to 256 KiB, 2048 packages are
# enough to show one taking 256 bytes
testCreateManyPackagesWithPreviousIndex()
{
    local repo="$TMPDIR/many" top="$TMPDIR/many.rpmbuild" i

    rm -rf $repo $top
    mkdir -p $repo $top
    # one spec builds the empty packages p0000 to p2047
    {
        printf 'Name: many\nVersion: 1\nRelease: 1\nSummary: many\nLicense: GPL\n'
        printf 'BuildArch: noarch\nAutoReqProv: no\n%%description\nmany\n'
        i=0
        while [ $i -lt 2048 ]; do
            printf '%%package -n p%04d\nSummary: p\n%%description -n p%04d\np\n%%files -n p%04d\n' $i $i $i
            i=$((i + 1))
        done
    } > $top/many.spec
    rpmbuild -bb --quiet --define "_topdir $top" --define "_builddir $top" \
        --define "_rpmdir $repo" --define '_buildhost localhost' \
        --define '_build_name_fmt %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm' \
        --define '_binary_payload w0.gzdio' $top/many.spec > $top/log 2>&1 || \
        fail "rpmbuild failed: $(tail -3 $top/log)"
    rm -rf $top

    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    (ulimit -s 256 && $POLDEK_NOCONF -s $repo --mkidx) || \
        fail "mkidx with the previous index failed"
    # -vvv names each package found in the previous index by its file...
    (ulimit -s 256 && $POLDEK_NOCONF -s $repo --mkidx -vvv > /dev/null) || \
        fail "mkidx -vvv failed"
    # ...and, when the time of the file differs, by its header
    touch -d '2001-01-01 00:00' $repo/*.rpm
    (ulimit -s 256 && $POLDEK_NOCONF -s $repo --mkidx -vvv > /dev/null) || \
        fail "mkidx -vvv of touched packages failed"
}

# an index that could not be written fails --mkidx and gets no digest
testCreateWriteError()
{
    local dir="$TMPDIR/write-error"

    rm -rf $dir
    mkdir $dir
    # with SIGXFSZ ignored, a write past the file size limit fails instead of killing poldek
    if (trap '' XFSZ; ulimit -f 1; $POLDEK_NOCONF -s $REPO --mkidx=$dir); then
        fail "mkidx succeeded"
    fi
    [ ! -f "$dir/packages.ndir.md" ] || fail "digest of an unwritten index"
    assert_no_tmp $dir
}

# descriptions that could not be written fail --mkidx too, though the index was
testCreateDescrWriteError()
{
    local dir="$TMPDIR/descr-write-error"

    rm -rf $dir
    # the descriptions cannot replace a directory of their name
    mkdir -p $dir/packages.ndir.dscr$COMPR_EXT
    if $POLDEK_NOCONF -s $REPO --mkidx=$dir; then
        fail "mkidx succeeded"
    fi
    die_if_empty_index "$dir/packages.ndir$COMPR_EXT"
    [ ! -f "$dir/packages.ndir.md" ] || fail "digest of unwritten descriptions"
    assert_no_tmp $dir
}

# no diff written means the digest must say brand-new: there is no list of
# diffs to take, so a client that does not know the index takes the whole one
testCreateNoDiffDigest()
{
    local repo="$TMPDIR/nodiff-digest"
    local last=$(ls $REPO/*.rpm | tail -1)

    mkrepo_but_last $repo
    cp $last $repo || fail "cp failed"
    $POLDEK_NOCONF -s $repo --mkidx --mo=nodiff || fail "mkidx failed"
    [ ! -e $repo/packages.i ] || fail "a diff was written"
    grep -q 'brand-new' $repo/packages.ndir.md || \
        fail "the digest does not say brand-new: $(cat $repo/packages.ndir.md)"
}

# a run that failed after the index was written leaves the index newer than
# its digest; the next run must notice the mismatch and publish the index,
# not leave the digest of the run before
testCreateRepairsStaleDigest()
{
    local repo="$TMPDIR/stale-digest" ref="$TMPDIR/stale-digest-ref"
    local last=$(ls $REPO/*.rpm | tail -1)

    mkrepo_but_last $repo
    cp $last $repo || fail "cp failed"
    if env LD_PRELOAD=$CLOSE_ERROR_SO WRITE_ERROR=packages.ndir.md \
        $POLDEK_NOCONF -s $repo --mkidx; then
        fail "mkidx succeeded"
    fi
    die_if_invalid_index $repo/packages.ndir$COMPR_EXT $(ls $REPO/*.rpm | wc -l)

    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx of the retry failed"

    # the digest the same packages get when the index is written from scratch
    rm -rf $ref
    mkdir $ref
    cp $repo/*.rpm $ref || fail "cp failed"
    $POLDEK_NOCONF -s $ref --mkidx || fail "mkidx of the reference failed"
    assertEquals "the digest of the repaired index" \
        "$(cat $ref/packages.ndir.md)" "$(cat $repo/packages.ndir.md)"
}

# a file of the index that cannot be written fails --mkidx and is left as it
# was, and so are the files after it: an index that fails leaves all of them,
# and as the digest is written last, the clients see the old index as
# current whichever file failed
testCreateErrorKeepsIndex()
{
    local repo="$TMPDIR/keep-index"
    local last=$(ls $REPO/*.rpm | tail -1)
    local n=$(ls $REPO/*.rpm | wc -l)
    local f before md fsum

    for f in packages.ndir$COMPR_EXT packages.ndir.dscr$COMPR_EXT packages.ndir.md; do
        mkrepo_but_last $repo
        before=$(index_sums $repo)
        md=$(cksum < $repo/packages.ndir.md)
        fsum=$(cksum < $repo/$f)
        cp $last $repo || fail "cp failed"

        if env LD_PRELOAD=$CLOSE_ERROR_SO WRITE_ERROR=$f $POLDEK_NOCONF -s $repo --mkidx; then
            fail "$f: mkidx succeeded"
        fi
        assert_no_tmp $repo
        [ ! -e $repo/packages.i ] || fail "$f: diff of an unwritten index"
        [ "$(cksum < $repo/$f)" = "$fsum" ] || fail "$f: replaced"
        [ "$(cksum < $repo/packages.ndir.md)" = "$md" ] || fail "$f: digest replaced"

        if [ "$f" = packages.ndir$COMPR_EXT ]; then
            [ "$(index_sums $repo)" = "$before" ] || fail "$f: index changed"
            die_if_invalid_index $repo/packages.ndir$COMPR_EXT $(expr $n - 1)
        else
            die_if_invalid_index $repo/packages.ndir$COMPR_EXT $n
        fi
    done
}

# a diff whose descriptions could not be written is not listed for the clients
testCreateDiffWriteError()
{
    local repo="$TMPDIR/write-error-diff"
    local last=$(ls $REPO/*.rpm | tail -1)
    local dscr

    rm -rf $repo $repo.copy
    mkdir $repo
    cp $REPO/*.rpm $repo || fail "cp failed"
    rm -f $repo/$(basename $last)
    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    cp $last $repo || fail "cp failed"

    # a diff's files are named after the time of the index it follows, so a
    # run on a copy tells the name of the diff's descriptions
    cp -a $repo $repo.copy
    $POLDEK_NOCONF -s $repo.copy --mkidx || fail "mkidx of the copy failed"
    dscr=$(cd $repo.copy && ls packages.i/packages.ndir.dscr.[0-9]*)
    [ -n "$dscr" ] || fail "no descriptions in the diff"

    mkdir -p $repo/$dscr
    if $POLDEK_NOCONF -s $repo --mkidx; then
        fail "mkidx succeeded"
    fi
    [ ! -f "$repo/packages.i/packages.ndir.diff.toc$COMPR_EXT" ] || fail "diff with unwritten descriptions listed"
}

# a diff whose list of diffs the clients read could not be written fails too
testCreateDiffTocWriteError()
{
    local repo="$TMPDIR/write-error-toc"
    local last=$(ls $REPO/*.rpm | tail -1)

    rm -rf $repo
    mkdir $repo
    cp $REPO/*.rpm $repo || fail "cp failed"
    rm -f $repo/$(basename $last)
    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    cp $last $repo || fail "cp failed"

    # a directory cannot replace packages.ndir.diff.toc<comp>
    mkdir -p $repo/packages.i/packages.ndir.diff.toc$COMPR_EXT
    if $POLDEK_NOCONF -s $repo --mkidx; then
        fail "mkidx succeeded"
    fi
}

# a digest whose close failed fails --mkidx; its bytes are written from the
# close of a stdio stream, so nothing else could report the bad write
testCreateDigestCloseError()
{
    local dir="$TMPDIR/digest-close-error" out rc

    rm -rf $dir
    mkdir $dir
    out=$(env LC_ALL=C LD_PRELOAD=$CLOSE_ERROR_SO WRITE_ERROR=packages.ndir.md \
        $POLDEK_NOCONF -s $REPO --mkidx=$dir 2>&1)
    rc=$?
    assertTrue "mkidx succeeded: $out" "[ $rc -ne 0 ]"
    assertTrue "no cause given: $out" "echo \"$out\" | grep -q 'unable to write digest: No space left on device'"
    die_if_empty_index "$dir/packages.ndir$COMPR_EXT"
    [ ! -f "$dir/packages.ndir.md" ] || fail "digest of a failed write"
    assert_no_tmp $dir
}

# a list of diffs whose close failed fails --mkidx and is not left cut
testCreateDiffTocCloseError()
{
    local repo="$TMPDIR/close-error-toc"
    local last=$(ls $REPO/*.rpm | tail -1)

    rm -rf $repo
    mkdir $repo
    cp $REPO/*.rpm $repo || fail "cp failed"
    rm -f $repo/$(basename $last)
    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    cp $last $repo || fail "cp failed"

    if env LD_PRELOAD=$CLOSE_ERROR_SO WRITE_ERROR=packages.ndir.diff.toc$COMPR_EXT \
        $POLDEK_NOCONF -s $repo --mkidx; then
        fail "mkidx succeeded"
    fi
    [ ! -f "$repo/packages.i/packages.ndir.diff.toc$COMPR_EXT" ] || fail "cut list of diffs left"
    assert_no_tmp $repo
}

cat_toc() {
    case $1 in
        *.gz)  zcat $1 ;;
        *.zst) zstdcat -q $1 ;;
        *)     cat $1 ;;
    esac
}

# the timestamp in the name of a file of a diff
tss_of() {
    echo $1 | grep -oE '[0-9]{4}\.[0-9]{2}\.[0-9]{2}-[0-9]{2}\.[0-9]{2}\.[0-9]{2}'
}

# every diff the list in $1 names is there
assert_listed_diffs() {
    local toc=$1 d

    for d in $(cat_toc $toc | cut -d' ' -f1); do
        [ -f $(dirname $toc)/$d ] || fail "listed $d missing"
    done
}

# next to the list in $1 are the files of the diffs it names, all of those
# among the files in $2, and no others
assert_diff_files() {
    local toc=$1 before=$2 dir=$(dirname $1) listed f t

    assert_listed_diffs $toc
    listed=$(cat_toc $toc | cut -d' ' -f1)
    for f in $(ls $dir); do
        t=$(tss_of $f)
        [ -n "$t" ] || continue
        echo "$listed" | grep -qF "$t" || fail "unlisted $f left"
    done

    for f in $before; do
        t=$(tss_of $f)
        [ -n "$t" ] || continue
        echo "$listed" | grep -qF "$t" || continue
        [ -e $dir/$f ] || fail "$f of a listed diff removed"
    done
}

# the total size of the diff files the list in $1 names
listed_size() {
    local toc=$1 total=0 d

    for d in $(cat_toc $toc | cut -d' ' -f1); do
        total=$((total + $(wc -c < $(dirname $toc)/$d)))
    done
    echo $total
}

# $1 with all the packages of $REPO but the last one, in $1.out, and an
# index with 6 diffs of the last one removed and added again, each about a
# quarter of the index
mkrepo_with_diffs() {
    local repo=$1 last=$(basename $(ls $REPO/*.rpm | tail -1)) i

    mkrepo_but_last $repo
    rm -rf $repo.out
    mkdir $repo.out
    cp $REPO/$last $repo.out || fail "cp failed"

    for i in 1 2 3; do
        mv $repo.out/$last $repo/ && $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
        mv $repo/$last $repo.out/ && $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    done
    die_if_invalid_index $repo/packages.i/packages.ndir.diff.toc$COMPR_EXT 6
}

# a list of diffs that cannot be read is replaced by a new one, not a reason
# for every --mkidx that changes the repo to fail
testCreateReplacesUnreadableToc()
{
    local repo="$TMPDIR/unreadable-toc"
    local toc="$repo/packages.i/packages.ndir.diff.toc$COMPR_EXT"
    local last=$(basename $(ls $REPO/*.rpm | tail -1))
    local out rc

    # an uncompressed list cut in two is still a list of some entries
    [ "$COMPR" = none ] && return

    mkrepo_with_diffs $repo
    head -c $(($(wc -c < $toc) / 2)) $toc > $toc.cut && mv $toc.cut $toc
    if cat_toc $toc >/dev/null 2>&1; then
        fail "the list of diffs is still readable"
    fi

    mv $repo.out/$last $repo/
    out=$($POLDEK_NOCONF -s $repo --mkidx 2>&1)
    rc=$?
    assertEquals "mkidx failed: $out" 0 "$rc"
    echo "$out" | grep -q 'starting a new one' || fail "no new list of diffs: $out"
    die_if_invalid_index $toc 1
    assert_listed_diffs $toc
    assert_no_tmp $repo
}

# a list of diffs is replaced only by a whole one: after a failure the
# clients find the old list, its diffs still there.  The diff of that run is
# missing from the list, so the next diff does not follow the last one
# listed, and the list starts again from it; out of testing mode the files
# of the diffs dropped go
testCreateDiffTocErrorKeepsList()
{
    local repo="$TMPDIR/keep-toc"
    local toc="$repo/packages.i/packages.ndir.diff.toc$COMPR_EXT"
    local last=$(basename $(ls $REPO/*.rpm | tail -1))
    local i before diffs out rc mo=$COMPR

    [ "$COMPR" = none ] && mo=nocompress    # out of testing mode

    mkrepo_with_diffs $repo
    before=$(cksum < $toc)
    diffs=$(ls $repo/packages.i)
    mv $repo.out/$last $repo/
    out=$(env -u POLDEK_TESTING LC_ALL=C LD_PRELOAD=$CLOSE_ERROR_SO \
        WRITE_ERROR=packages.ndir.diff.toc$COMPR_EXT \
        $POLDEK_NOCONF -s $repo --mkidx --mo=$mo 2>&1)
    rc=$?
    assertTrue "mkidx succeeded: $out" "[ $rc -ne 0 ]"
    assertTrue "no cause given: $out" "echo \"$out\" | grep -q 'unable to write the list of diffs: No space left on device'"
    [ "$(cksum < $toc)" = "$before" ] || fail "list of diffs changed"
    for i in $diffs; do
        [ -e $repo/packages.i/$i ] || fail "$i removed"
    done
    assert_listed_diffs $toc
    assert_no_tmp $repo

    diffs=$(ls $repo/packages.i)
    mv $repo/$last $repo.out/
    out=$(env -u POLDEK_TESTING LC_ALL=C $POLDEK_NOCONF -s $repo --mkidx --mo=$mo 2>&1)
    rc=$?
    assertTrue "mkidx failed: $out" "[ $rc -eq 0 ]"
    assertTrue "no warning: $out" "echo \"$out\" | grep -q 'a diff is missing from the list'"
    die_if_invalid_index $toc 1
    assert_diff_files $toc "$diffs"
}

# out of testing mode a diff that adds packages trims the list, and the
# files of the diffs it no longer names are removed, their descriptions too
testCreateDiffTocVaccum()
{
    local repo="$TMPDIR/vaccum"
    local toc="$repo/packages.i/packages.ndir.diff.toc$COMPR_EXT"
    local last=$(basename $(ls $REPO/*.rpm | tail -1))
    local diffs out rc n oldest limit kept

    # the uncompressed index would take 30 diffs and more
    [ "$COMPR" = none ] && return

    mkrepo_with_diffs $repo
    diffs=$(ls $repo/packages.i)
    mv $repo.out/$last $repo/
    out=$(env -u POLDEK_TESTING LC_ALL=C $POLDEK_NOCONF -s $repo --mkidx --mo=$COMPR 2>&1)
    rc=$?
    assertTrue "mkidx failed: $out" "[ $rc -eq 0 ]"
    # the chain is whole: only the size trims the list, no diff is dropped
    # for leading nowhere
    assertTrue "gap warning: $out" "! echo \"$out\" | grep -q 'a diff is missing from the list'"
    n=$(cat_toc $toc | wc -l)
    [ $n -lt 7 ] || fail "list of diffs not trimmed"
    assert_diff_files $toc "$diffs"

    # the kept diffs alone pass 90% of the index, and without the oldest kept
    # one they do not: a diff that still fits was dropped or one that does not
    # was kept
    oldest=$(cat_toc $toc | cut -d' ' -f1 | head -1)
    limit=$(( $(wc -c < $repo/packages.ndir$COMPR_EXT) * 9 / 10 ))
    kept=$(listed_size $toc)
    [ $kept -gt $limit ] || fail "list overtrimmed: $kept <= $limit"
    [ $((kept - $(wc -c < $repo/packages.i/$oldest))) -le $limit ] || \
        fail "an older diff than fits is kept: $kept"

    assert_no_tmp $repo
}

# the temporary files of the index a killed --mkidx left are removed by the
# next one that writes it; a fresh one may be another --mkidx's, and other files are not
# the index's
testCreateRemovesStaleTmps()
{
    local repo="$TMPDIR/stale-tmps" f

    mkrepo_but_last $repo
    mkdir -p $repo/packages.i
    for f in .packages.ndir$COMPR_EXT.tmp.AAAAAA .packages.ndir.md.tmp.BBBBBB \
             packages.i/.packages.ndir.diff.toc$COMPR_EXT.tmp.CCCCCC; do
        echo cut > $repo/$f
        touch -d '-2 hours' $repo/$f
    done
    echo fresh > $repo/.packages.ndir.md.tmp.DDDDDD
    echo other > $repo/.other.tmp.EEEEEE
    touch -d '-2 hours' $repo/.other.tmp.EEEEEE

    cp $(ls $REPO/*.rpm | tail -1) $repo || fail "cp failed"
    $POLDEK_NOCONF -s $repo --mkidx || fail "mkidx failed"
    for f in .packages.ndir$COMPR_EXT.tmp.AAAAAA .packages.ndir.md.tmp.BBBBBB \
             packages.i/.packages.ndir.diff.toc$COMPR_EXT.tmp.CCCCCC; do
        [ ! -e $repo/$f ] || fail "$f left"
    done
    [ -f $repo/.packages.ndir.md.tmp.DDDDDD ] || fail "fresh temporary file removed"
    [ -f $repo/.other.tmp.EEEEEE ] || fail "file of no index removed"
}

#  b) --st rpmdb -s /foo          =>  rpmdb -> default type
testCreateFromRpmdb() {
    skip_if_rpm_testing_off && return

    rm -rf $TMPDIR/tmproot
    mkdir $TMPDIR/tmproot
    $SUDO rpm --root=$TMPDIR/tmproot --initdb

    local rpmop=
    test is_verbose_mode && rpmop="v"

    msgn "prep: rpm install"
    $SUDO rpm --root=$TMPDIR/tmproot -U$rpmop $SOURCE_REPO/sh-*.rpm --noscripts
    for p in $(ls $SOURCE_REPO/a*.rpm); do
        $SUDO rpm --root=$TMPDIR/tmproot -U$rpmop $p --noscripts
    done

    msgn "test"
    $POLDEK_NOCONF --st rpmdb -s $TMPDIR/tmproot/var/lib/rpm --index=$TMPDIR/tmproot/packages.ndir$COMPR_EXT || fail "mkidx failed"
    die_if_empty_index "$TMPDIR/tmproot/packages.ndir$COMPR_EXT"
    check_repo_content $TMPDIR/tmproot
}

#  d) -s /foo --mt dtype        =>  dir  -> dtype
#  e) -s /foo --mt dtype,dtype2 =>  dir  -> dtype
xtestSelectType() # disabled as pdir indexes are gone since 0.4
{
    msgn "$Case_d"
    $POLDEK_NOCONF -s $REPO --mkidx --mt pdir || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.dir$COMPR_EXT"

    rm -rf $REPO/packages.*
    $POLDEK_NOCONF -s $REPO --st dir --mkidx --mt pdir || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.dir$COMPR_EXT"

    setUp

    msgn "$Case_e"
    $POLDEK_NOCONF -s $REPO --mkidx --mt pdir,pndir || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.ndir$COMPR_EXT"
    die_if_empty_index "$REPO/packages.dir$COMPR_EXT"
}

poldek_n() {
    $POLDEK_NOCONF -Osource1="repo-pndir,type=pndir $REPO"  $@
}

#  f) -n foo                    =>  dir (or original type) -> foo's type
testCreateByName()
{
    msgn "$Case_f"
    poldek_n -n repo-pndir --mkidx || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.ndir$COMPR_EXT"
}

#  g) -s /foo --mkidx=<path>
testNonDefaultName()
{
    msgn "$Case_g"
    poldek="$POLDEK_NOCONF"

    msgn "1"
    $poldek -s $REPO --mkidx=$TMPDIR || fail "mkidx #1 failed"
    die_if_empty_index "$TMPDIR/packages.ndir$COMPR_EXT"

    msgn "2"
    $poldek -s $REPO --mkidx=$TMPDIR/packages.foo.ndir$COMPR_EXT || fail "mkidx #2 failed"
    die_if_empty_index "$TMPDIR/packages.foo.ndir$COMPR_EXT"

    msgn "3"
    $poldek --st pndir -s $TMP/packages.foo.ndir$COMPR_EXT \
            --mkidx=$TMP/packages.foo2.ndir$COMPR_EXT --mt pndir || fail "mkidx #3 failed"

    die_if_empty_index "$TMP/packages.foo2.ndir$COMPR_EXT"

    setUp
    msgn "4"
    $poldek -s $REPO --mkidx --mt pndir || fail "mkidx #4 failed"

    msgn "5"
    poldek="$POLDEK_UP -Ovfile_retries=1"
    $poldek --st pndir -s $REPOURL --mkidx=$TMPDIR || fail "mkidx #5 failed"
    die_if_empty_index "$TMPDIR/packages.ndir$COMPR_EXT"

    msgn "6"
    $poldek --st pndir -s $REPOURL --mkidx=$TMPDIR/packages.foo.ndir$COMPR_EXT || fail "mkidx #6 failed"
    die_if_empty_index "$TMPDIR/packages.foo.ndir$COMPR_EXT"
}

#  h) -n foo --mkidx=<path>
testCreateFromRemoteRepos()
{
    msgn "$Case_h"
    poldek_n -n repo-pndir --mkidx=$TMPDIR/packages.foo.ndir$COMPR_EXT --mt pndir ||
        fail "mkidx #1 failed"
    die_if_empty_index "$TMPDIR/packages.foo.ndir$COMPR_EXT"

    poldek_n -n repo-pndir --mkidx=$TMPDIR/packages.foo2.ndir$COMPR_EXT --mt pndir ||
        fail "mkidx #2 failed"

    die_if_empty_index "$TMPDIR/packages.foo2.ndir$COMPR_EXT"
}

# a merged index from several sources is not written when one fails to load
testCreateMergedWithMissingSource()
{
    msgn "--st dir -s /missing --st dir -s /foo --mkidx=<path>"
    rm -rf $TMPDIR/merged
    mkdir $TMPDIR/merged

    # sources go in path order, so the missing one is loaded first
    $POLDEK_NOCONF --st dir -s $TMPDIR/missing --st dir -s $REPO --mkidx=$TMPDIR/merged &&
        fail "mkidx with a missing source succeeded"
    [ -z "$(ls $TMPDIR/merged)" ] || fail "index written: $(ls $TMPDIR/merged)"
}

testCreateConfiguredDefaultIndexCompr()
{
    msgn "with 'default index compr' = zst"
    echo "
[global]
default index compr = zst
" >> $TMPDIR/poldek.conf

    if [ -n "$POLDEK_TESTING_INDEX_COMPR" ]; then # unset global
        force_msg " => compression is set globally, skipped"
        return;
    fi

    $POLDEK --conf $TMPDIR/poldek.conf -s $REPO --mkidx || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.ndir.zst"
}

testCreateWithIndexComprOption()
{
    compr="$POLDEK_TESTING_INDEX_COMPR"
    if [ -n "$POLDEK_TESTING_INDEX_COMPR" ]; then # unset global
        unset POLDEK_TESTING_INDEX_COMPR
    fi

    op=""
    if [ "$compr" == "zst" ]; then
        op="zstd"
    elif [ "$compr" == "gz" ]; then
        op="gzip"
    elif [ "$compr" == "none" ]; then
        op="nocompress"
    else
        op="gzip"
    fi

    msgn "with --mo=$op"

    $POLDEK_NOCONF -s $REPO --mkidx --mo=$op || fail "mkidx failed"
    die_if_empty_index "$REPO/packages.ndir$COMPR_EXT"
}

# poldek stops when rpm cannot read its configuration, instead of going on
# with an unconfigured rpm and the umask the failed read left at 0
testCreateWithoutRpmConfig()
{
    local dir=$TMPDIR/no-rpm-config out rc

    rm -rf $dir && mkdir $dir || fail "mkdir failed"
    out=$(umask 077; RPM_CONFIGDIR=$dir/none $POLDEK_NOCONF -s $REPO --mkidx=$dir 2>&1)
    rc=$?
    assertTrue "exit code 0 without rpm configuration: $out" "[ $rc -ne 0 ]"
    assertEquals "files left in $dir" "" "$(ls -A $dir)"
}


. ./sh/lib/shunit2
