#!/bin/sh
# $Id$

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

up() {
   poldek_up -Oautoupa=n --up || fail "up failed"
}

# simulate locally cached package
fetch_package_to_cachedir()
{
    msgn "download package to cachedir"
    package=$(poldek_quiet_up -q --cmd 'ls -q' | head -1)
    [ -n "$package" ] || fail "no available packages??"

    msg "  - $package"
    poldek_up --cmd "get -d $CACHEDIR $package"
    downloaded=$(find $CACHEDIR -name $package\*.rpm | wc -l)
    assertEquals "$package not downloaded?" "1" $downloaded

    # no simply way to fetch packages to local repo cache1
    index=$(find $CACHEDIR -name packages.ndir.gz)
    REPO_CACHE_DIR=$(dirname $index)
    cp -L $CACHEDIR/$package*.rpm $REPO_CACHE_DIR # symlinked by test fetcher
    rm -f $CACHEDIR/$package*.rpm
}

setUp()
{
    tearDown # from lib/repo-setup
    POLDEK_TESTING_DENIED_FILES="packages.ndir.diff.toc"

    msgn "Creating repo"
    indexfile="$REPO/packages.ndir.gz"
    $POLDEK_NOCONF -s $REPO --mkidx --mt pndir || fail "mkidx failed"
    die_if_empty_index $indexfile
    rm -rf $CACHEDIR
}

testCleanCache()
{
    msgn "up"
    up

    n=$(find $CACHEDIR -type f | wc -l)
    # 8 files should be present:
    #  1. packages.ndir.md (remote)
    #  2. packages.ndir.gz (remote)
    #  3. packages.ndir.gz.md5 (local)
    #  4. packages.ndir.dscr.gz (remote)
    #  5. packages.ndir.dscr.gz.md5 (local)
    #  6. dirindex.pndir.tndb (local)
    #  7. dirindex.pndir.tndb.md5 (local)
    #  8. stubindex.pndir.zst (local)
    assertEquals "index not downloaded?" "$n" "8"

    fetch_package_to_cachedir

    #find $CACHEDIR
    n=$(find $CACHEDIR -type f | wc -l)
    assertEquals "index and package not downloaded?" "$n" "9"

    msgn "clean"
    touch $CACHEDIR/foo.txt     # some arbitrary file
    poldek_up --clean

    n=$(find $CACHEDIR -type f | wc -l)
    [ "$n" != "0" ] && find $CACHEDIR/
    assertEquals "$n files left in cache" "$n" "0"
}

testCleanRepoCache()
{
    msgn "up"
    up

    n=$(find $CACHEDIR -type f | wc -l)
    assertEquals "index not downloaded?" "$n" "8"

    fetch_package_to_cachedir

    n=$(find $CACHEDIR -type f | wc -l)
    assertEquals "index and package not downloaded?" "$n" "9"

    msgn "clean"
    poldek_up -n $REPONAME --clean

    n=$(find $CACHEDIR -type f | wc -l)
    [ "$n" != "0" ] && find $CACHEDIR/
    assertEquals "$n files left in cache" "$n" "0"
}

. ./sh/lib/shunit2
