#!/bin/sh
# $Id$

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

create_local_conf() {
echo "
_name_prefix = test

[source]
name = %{_name_prefix}1
type = pndir
path = ${REPOURL}1

[source]
name = %{_name_prefix}2
type = pdir
path = ${REPOURL}2
" > $TMPDIR/poldek.conf
}

testConf()
{
    #cat $TMPDIR/poldek.conf
    create_local_conf
    poldek_l="$POLDEK --conf $TMPDIR/poldek.conf -q  -l"

    is_verbose_mode && $poldek_l

    n=$($poldek_l | grep 'test://' | wc -l)
    assertEquals "2 sources expected" "$n" "2"

    n=$($poldek_l | grep -E '^test[12] ' | wc -l)
    assertEquals "2 sources expected, but not those" "$n" "2"
}

# argp loops or crashes on --help below about 38 columns; poldek gives it at least 40
testHelpNarrowTerminal()
{
    if ! command -v script >/dev/null; then
        msgn "no script(1), skipped this test"
        return 0
    fi

    typeset out
    out=$(timeout 10 script -qec "stty cols 20; $POLDEK --help" /dev/null </dev/null 2>&1)
    typeset rc=$?
    if [ "$rc" -ne 0 ]; then
        echo "$out" >&2
        fail "--help on a 20-column terminal failed with exit $rc"
    fi
}

# with stdout a pipe or a pty with no size set, the width comes from $COLUMNS
# env(1) sets and drops it: mksh, which /bin/sh may be, ignores an empty
# COLUMNS= assignment and passes the inherited value on
testListSourcesColumns()
{
    path="/nonexistent/$(printf 'long-directory-name-%02d/' 1 2 3 4 5)repo"

    out=$(env COLUMNS=500 $POLDEK --noconf -s $path --st dir -l)
    echo "$out" | grep -qF "$path" || fail "path shortened with COLUMNS=500: $out"

    out=$(env -u COLUMNS $POLDEK --noconf -s $path --st dir -l)
    echo "$out" | grep -qF '[...]' || fail "path not shortened to 80 columns: $out"

    # script(1) run without a terminal gives a pty with no size set
    if command -v script >/dev/null; then
        out=$(env COLUMNS=500 script -qec "$POLDEK --noconf -s $path --st dir -l" /dev/null </dev/null)
        echo "$out" | grep -qF "$path" || fail "path shortened on a pty with no size: $out"
    fi
}

testListSourcesCompr()
{
    echo "
[source]
name = zst
type = pndir
path = /nonexistent/repo/
compr = zst
" > $TMPDIR/compr.conf

    out=$($POLDEK --conf $TMPDIR/compr.conf -l 2>&1) || fail "-l failed with exit $?: $out"
    echo "$out" | grep -qF 'compr=zst' || fail "compr=zst not listed: $out"

    # a value poldek does not know is refused when the configuration is
    # read, and the source keeps the default
    sed -i 's/^compr = zst$/compr = bogus/' $TMPDIR/compr.conf
    out=$($POLDEK --conf $TMPDIR/compr.conf -l 2>&1)
    echo "$out" | grep -qF "invalid value 'bogus' of 'source::compr'" ||
        fail "compr = bogus not refused: $out"
    if echo "$out" | grep -qF 'compr=bogus'; then
        fail "compr=bogus listed: $out"
    fi
}

# [source] has only "signed", which stands for gpg and pgp too
testLegacySourceOptions()
{
    echo "
[global]
source = legacygpg,pri=7,gpg,compr=zst /nonexistent/repo1/
source = legacypgp,pgp /nonexistent/repo2/
" > $TMPDIR/legacy.conf

    out=$($POLDEK --conf $TMPDIR/legacy.conf -l 2>&1) || fail "-l failed with exit $?: $out"
    for o in pri=7 sign compr=zst; do
        echo "$out" | grep -E '^legacygpg ' | grep -qF "$o" || fail "legacygpg: $o not listed: $out"
    done
    echo "$out" | grep -E '^legacypgp ' | grep -qF sign || fail "legacypgp: sign not listed: $out"
}

# same option given on the command line, in the "name,opt path" syntax
testListSourcesComprFromCommandLine()
{
    out=$($POLDEK --noconf -s "zst,compr=zst /nonexistent/repo/" --st dir -l 2>&1) || fail "-l with -s failed with exit $?: $out"
    echo "$out" | grep -qF 'compr=zst' || fail "compr=zst from -s not listed: $out"
}

# a legacy "source = name,opt path" line keeps the value, not just the fact
testListSourcesComprLegacyLine()
{
    printf '%s\n' "[global]" "source = zst,compr=zst /nonexistent/repo/" > $TMPDIR/compr-legacy.conf

    out=$($POLDEK --conf $TMPDIR/compr-legacy.conf -l 2>&1) || fail "-l failed with exit $?: $out"
    echo "$out" | grep -qF 'compr=zst' || fail "compr=zst from a legacy source line not listed: $out"
}

testConfAsRoot()
{
    if command -v ldd >/dev/null; then
        if ldd $POLDEK_RAW | grep -q asan; then
            msgn "asan detected, skipped this test"
            return 0
        fi
    fi

    create_local_conf
    msgn "--conf"
    poldek_l="$POLDEK --conf $TMPDIR/poldek.conf -q  -l"

    is_verbose_mode && $poldek_l

    n=$(fakeroot $poldek_l | grep 'test://' | wc -l)
    assertEquals "2 sources expected" "$n" "2"

    n=$(fakeroot $poldek_l | grep -E '^test[12] ' | wc -l)
    assertEquals "2 sources expected, but not those" "$n" "2"

    msgn "default conf"
    mkdir $TMPDIR/home || fail "mkdir"
    mv -f $TMPDIR/poldek.conf $TMPDIR/home/.poldekrc
    HOME=$TMPDIR/home
    export HOME

    poldek_l="$POLDEK -q -l"
    is_verbose_mode && $poldek_l

    n=$(fakeroot $poldek_l | grep 'test://' | wc -l)
    assertEquals "2 sources expected" "$n" "2"

    n=$(fakeroot $poldek_l | grep -E '^test[12] ' | wc -l)
    assertEquals "2 sources expected, but not those" "$n" "2"
}

testConfMacros()
{
    echo "
_arch   = x86_64
_snap	= 2019
_prefix = https://test/dists/th/%{_snap}

[source]
type   = pndir
name   = th-%{_snap}
path   = %{_prefix}/PLD/%{_arch}/RPMS/
" > $TMPDIR/macros.conf

    local source_url=$($POLDEK --conf $TMPDIR/macros.conf -l | awk '{print $2}')
    local url="https://test/dists/th/2019/PLD/x86_64/RPMS/"
    assertEquals "expected $url, got $source_url" "$source_url" "$url"
}

testConfMacrosNested()
{
    echo "
_arch   = x86_64
_snap	= 2019
_zprefix = https://test/dists/th/%{_snap}
_prefix = %{_zprefix}

[source]
type   = pndir
name   = th-%{_snap}
path   = %{_prefix}/PLD/%{_arch}/RPMS/
" > $TMPDIR/macros.conf

    local source_url=$($POLDEK --conf $TMPDIR/macros.conf -l | grep -P '^th-2019' | awk '{print $2}')
    local url="https://test/dists/th/2019/PLD/x86_64/RPMS/"
    assertEquals "expected $url, got $source_url" "$source_url" "$url"
}

testConfArchMacroDefault()
{
    local arch=$(rpm --eval '%{_target_cpu}')

    echo "
[source]
type = pndir
name = default-arch
path = /repo/%{_arch}/RPMS/
" > $TMPDIR/arch-default.conf

    local source_url=$($POLDEK --conf $TMPDIR/arch-default.conf -l | awk '/^default-arch/ {print $2}')
    local url="/repo/${arch}/RPMS/"
    assertEquals "expected $url, got $source_url" "$source_url" "$url"
}

testConfArchMacroShadow()
{
    echo "
_arch = foo

[source]
type = pndir
name = shadow-arch
path = /repo/%{_arch}/RPMS/
" > $TMPDIR/arch-shadow.conf

    local source_url=$($POLDEK --conf $TMPDIR/arch-shadow.conf -l | awk '/^shadow-arch/ {print $2}')
    local url="/repo/foo/RPMS/"
    assertEquals "expected $url, got $source_url" "$source_url" "$url"
}

testConfInclude()
{
    #cat $TMPDIR/poldek.conf
    create_local_conf
    conf="$TMPDIR/poldek.conf"
    poldek_l="$POLDEK --conf $conf -q -l"
    cp $conf $conf.orig

    msgn "%include foo.conf"

    echo -e "[global]\n%include source.conf\n" > $conf
    cat $conf.orig >> $conf
    echo -e "[source]\nname=test3\ntype=pndir\npath=test:///foo/bar/z\n" > $TMPDIR/source.conf

    is_verbose_mode && $poldek_l

    n=$($poldek_l | grep 'test://' | wc -l)
    assertEquals "3 sources expected, got $n" "$n" "3"

    n=$($poldek_l | grep -E '^test[123] ' | wc -l)
    assertEquals "3 sources expected, but not those" "$n" "3"


    msgn "%include /bar/baz/foo.conf"

    echo -e "[global]\n%include $REPO/source-abs.conf\n" > $conf
    cat $conf.orig >> $conf
    echo -e "[source]\nname=test4\ntype=pndir\npath=test:///foo/bar/z\n" > $REPO/source-abs.conf
    is_verbose_mode && $poldek_l

    n=$($poldek_l | grep 'test://' | wc -l)
    assertEquals "3 sources expected, got $n" "$n" "3"

    n=$($poldek_l | grep -E '^test[124] ' | wc -l)
    [ "$n" == "3" ] && assertEquals "3 sources expected, but not those" "$n" "3"
}


# macros are local to the file that declares them, also across %include: the
# includer's _name_prefix does not leak into the included file, nor the other
# way round
testIncludeAndMacros()
{
    create_local_conf

    cat > $TMPDIR/included.conf <<EOF
_name_prefix = xtest

[source]
name = %{_name_prefix}1
type = pndir
path = ${REPOURL}x1

[source]
name = %{_name_prefix}2
type = pdir
path = ${REPOURL}x2
EOF

    cat >> $TMPDIR/poldek.conf <<EOF

[global]
%include $TMPDIR/included.conf

[source]
name = %{_name_prefix}3
type = pndir
path = ${REPOURL}3

[source]
name = %{_name_prefix}4
type = pdir
path = ${REPOURL}4
EOF

    poldek_l="$POLDEK --conf $TMPDIR/poldek.conf -q -l"
    is_verbose_mode && $poldek_l

    n=$($poldek_l | grep 'test://' | wc -l)
    assertEquals "6 sources expected, got $n" "$n" "6"

    n=$($poldek_l | grep -E '^test[1234] ' | wc -l)
    assertEquals "4 test sources expected, got $n" "$n" "4"

    n=$($poldek_l | grep -E '^xtest[12] ' | wc -l)
    assertEquals "2 xtest sources expected, got $n" "$n" "2"
}

# a remote configuration is not read at load time any more: it is added once
# with repo add and kept in repos.d
testRemoteIncludeRefused()
{
    cat > $TMPDIR/remote-include.conf <<EOF
[global]
%include http://example.com/remote.conf
EOF

    out=$($POLDEK --conf $TMPDIR/remote-include.conf -q -l 2>&1)
    rc=$?
    assertEquals "a remote %include should fail: $out" "1" "$rc"
    echo "$out" | grep -q "a remote configuration is not included" || \
        fail "no reason given: $out"
    echo "$out" | grep -q "poldek repo add http://example.com/remote.conf" || \
        fail "no hint to repo add: $out"

    cat > $TMPDIR/remote-includedir.conf <<EOF
[global]
%includedir http://example.com/repos.d
EOF

    out=$($POLDEK --conf $TMPDIR/remote-includedir.conf -q -l 2>&1)
    rc=$?
    assertEquals "a remote %includedir should fail: $out" "1" "$rc"
    echo "$out" | grep -q "a remote configuration is not included" || \
        fail "no reason given: $out"
}

# nor is a remote configuration taken as the configuration itself
testRemoteConfRefused()
{
    out=$($POLDEK --conf http://example.com/poldek.conf -q -l 2>&1)
    rc=$?
    assertEquals "a remote --conf should fail: $out" "1" "$rc"
    echo "$out" | grep -q "a remote configuration is not read" || \
        fail "no reason given: $out"
    echo "$out" | grep -q "poldek repo add http://example.com/poldek.conf" || \
        fail "no hint to repo add: $out"
}

# --upconf went with the remote configurations
testUpconfRemoved()
{
    out=$($POLDEK --upconf -q -l 2>&1)
    if [ "$?" -eq 0 ]; then
        fail "--upconf should not be accepted: $out"
    fi
    echo "$out" | grep -q "upconf" || fail "no reason given: $out"
    $POLDEK --help 2>&1 | grep -q -- "--upconf" && fail "--upconf is still in --help"
    return 0
}

# argp prints the bug address only if it can see poldek's argp_program_bug_address
testHelpShowsBugAddress()
{
    out=$(LC_ALL=C $POLDEK --help)
    echo "$out" | grep -q "^Report bugs to " || fail "no bug address in --help: $(echo "$out" | tail -2)"
}

# A plain %%includedir directive in a regular config is followed.
testConfIncludedir()
{
    local conf=$TMPDIR/includedir.conf
    local includedir=$TMPDIR/includedir.d
    rm -rf $includedir
    mkdir -p $includedir

    cat > $conf <<EOF
[global]
%includedir $includedir
EOF

    cat > $includedir/a.conf <<EOF
[source]
name = alpha
type = pndir
path = test:///alpha
EOF

    cat > $includedir/b.conf <<EOF
[source]
name = beta
type = pndir
path = test:///beta
EOF

    $POLDEK --conf $conf -q -l > $TMPDIR/includedir-out 2>&1 || true

    grep -q '^alpha ' $TMPDIR/includedir-out || fail "alpha_source_not_loaded"
    grep -q '^beta ' $TMPDIR/includedir-out || fail "beta_source_not_loaded"
}

# %include takes a directory: every *.conf in it is included, others ignored
testConfIncludeDir()
{
    local conf=$TMPDIR/include-dir.conf
    local dir=$TMPDIR/include-dir.d

    rm -rf $dir
    mkdir -p $dir

    cat > $dir/a.conf <<EOF
[source]
name = incdir-a
type = pndir
path = test:///incdir/a
EOF

    cat > $dir/b.conf <<EOF
[source]
name = incdir-b
type = pndir
path = test:///incdir/b
EOF

    echo "neither a section nor a parameter" > $dir/c.txt

    cat > $conf <<EOF
[global]
%include $dir
EOF

    $POLDEK --conf $conf -q -l > $TMPDIR/include-dir-out 2>&1 || true
    grep -q '^incdir-a ' $TMPDIR/include-dir-out || \
        fail "first source not loaded: $(cat $TMPDIR/include-dir-out)"
    grep -q '^incdir-b ' $TMPDIR/include-dir-out || \
        fail "second source not loaded: $(cat $TMPDIR/include-dir-out)"
}

# a directory included with a relative path is resolved against the includer
testConfIncludeRelativeDir()
{
    local conf=$TMPDIR/relative.conf
    local dir=$TMPDIR/relative.d

    rm -rf $dir $conf
    mkdir -p $dir

    cat > $dir/rel.conf <<EOF
[source]
name = incdir-rel
type = pndir
path = test:///incdir/rel
EOF

    cat > $conf <<EOF
[global]
%include relative.d
EOF

    $POLDEK --conf $conf -q -l > $TMPDIR/relative-out 2>&1 || true
    grep -q '^incdir-rel ' $TMPDIR/relative-out || \
        fail "a relative directory not resolved: $(cat $TMPDIR/relative-out)"
}

# include paths are resolved once: --conf may itself be a relative path with
# a directory component, and a relative %include must still name its includer
testConfIncludeRelativeConf()
{
    local dir=$TMPDIR/relconf.d
    local out rc

    rm -rf $dir
    mkdir -p $dir/sub/sub

    printf '[source]\nname = right\ntype = pndir\npath = test:///right\n' \
        > $dir/sub/inc.conf
    # a second resolution would load this one instead
    printf '[source]\nname = wrong\ntype = pndir\npath = test:///wrong\n' \
        > $dir/sub/sub/inc.conf
    printf '[global]\n%%include inc.conf\n' > $dir/sub/main.conf

    out=$(cd $dir && $POLDEK --conf sub/main.conf -q -l 2>&1)
    rc=$?
    assertEquals "a relative --conf should load: $out" "0" "$rc"
    echo "$out" | grep -q '^right ' || \
        fail "an include was not resolved against its includer: $out"
    if echo "$out" | grep -q '^wrong '; then
        fail "an include was resolved twice: $out"
    fi
}

# %includedir is the older name of %include, so it takes a file as well
testConfIncludedirWithFile()
{
    local conf=$TMPDIR/includedir-file.conf
    local inc=$TMPDIR/includedir-file.inc

    cat > $inc <<EOF
[source]
name = incdir-file
type = pndir
path = test:///incdir/file
EOF

    cat > $conf <<EOF
[global]
%includedir $inc
EOF

    $POLDEK --conf $conf -q -l > $TMPDIR/includedir-file-out 2>&1 || true
    grep -q '^incdir-file ' $TMPDIR/includedir-file-out || \
        fail "a file not included by %includedir: $(cat $TMPDIR/includedir-file-out)"
}

# Files in the built-in repos.d must not follow %%includedir directives.
testReposdIgnoresIncludedir()
{
    local reposd=$TMPDIR/reposd
    rm -rf $reposd
    mkdir -p $reposd/include $TMPDIR/home

    cat > $reposd/managed.conf <<EOF
# remote repository managed by poldek
[source]
name = managed
type = pndir
path = test:///managed

%includedir $reposd/include
EOF

    cat > $reposd/include/extra.conf <<EOF
[source]
name = extra
type = pndir
path = test:///extra
EOF

    touch $TMPDIR/home/.poldekrc
    POLDEK_TESTING_REPOSDIR=$reposd HOME=$TMPDIR/home $POLDEK -q -l > $TMPDIR/reposd-out 2>&1 || true

    grep -q '^managed ' $TMPDIR/reposd-out || fail "managed_source_not_loaded"
    if grep -q '^extra ' $TMPDIR/reposd-out; then
        fail "includedir_was_followed"
    fi
}

# A configuration may include the built-in repos.d itself; the files are then
# read once instead of failing with "included twice", and the redundant
# directive is reported
testReposdIncludedByConfig()
{
    local reposd=$TMPDIR/reposd-self
    rm -rf $reposd
    mkdir -p $reposd $TMPDIR/home

    cat > $reposd/self.conf <<EOF
[source]
name = self
type = pndir
path = test:///self
EOF

    cat > $TMPDIR/home/.poldekrc <<EOF
[global]
%includedir $reposd
EOF

    POLDEK_TESTING_REPOSDIR=$reposd HOME=$TMPDIR/home $POLDEK -q -l > $TMPDIR/self-out 2>&1
    assertEquals "the configuration should load" "0" "$?"
    assertEquals "the source should be listed once" "1" \
        "$(grep -c '^self ' $TMPDIR/self-out)"
    grep -q 'repos.d is read automatically' $TMPDIR/self-out || \
        fail "no warning about the redundant include"
}

. ./sh/lib/shunit2
