#!/usr/bin/bash
#
# Run tests, the jenkins way.
#
# Usage: run-tests [-q] [nosetests options]
#
#    -q  Don't run static checks, just run test
#
# Requires: python-virtualenv, python-pip, python-unitttest2
#    python-nose, rpmlint, devscripts-minimal, packagedb-cli

function install_virtenv()
{
    echo "Installing new virtual env"
    rm -fr fedorareviewenv
    python3 -m venv --system-site-packages fedorareviewenv
    source fedorareviewenv/bin/activate

    pip install --upgrade pip
    pip install -q nose --upgrade --force ## Needed within the venv
    pip install -q nosexcover --upgrade

    hash -r  ## Reload where the nosetests app is (within the venv)
}
#   pip install nose-cov --upgrade

function init_mockroot()
{
    if [ "$1" = '-' ]; then
       shift
       if (( $# == 0 )); then
          root=''
          rootmsg=default
       else
          root="$*"
          rootmsg="$*"
       fi
    else
       root="-r $*"
       rootmsg="$*"
    fi
    mock -q $root --chroot --  "echo $rootmsg OK >/dev/null" || {
        echo "Re-initializing mock root $rootmsg"
        mock -q $root  --init
    }
}

if [ "$1" = '-q' ]; then
    quick=1
    REVIEW_NOSEWITH=${REVIEW_NOSEWITH:- -x}
    shift
fi
args="$@"

export PATH=/bin:/usr/bin:/sbin:/usr/sbin

cd $(dirname $(readlink -fn $0))
cd ..

test -d $PWD/dist || mkdir $PWD/dist
logfile="$PWD/dist/build.log"
( {
    if [[ -n "$PIP_INSTALL" || ! -d fedorareviewenv ]]; then
        install_virtenv
    fi
    source fedorareviewenv/bin/activate
    hash -r

    PYTHONPATH=src ./update-version || :
    cd test
        export REVIEW_LOGLEVEL=${REVIEW_LOGLEVEL:-warning}
        for root in '-' fedora-42-x86_64 fedora-43-x86_64 \
                    "- --uniqueext=hugo"
        do
            init_mockroot $root
        done

        echo "Running tests:"
        ln -sf ../fedorareviewenv .
        PYTHONPATH=../src:./fedorareviewenv/lib/python3.*/site-packages:./fedorareviewenv/lib64/python3.*/sitepackages \
        python -m pytest -vv "${args[@]}"
        status=$?
        deactivate
    cd ..
    if [ -z "$quick" ]; then
        echo
        echo '---- pylint ----'
        MSG_TEMPLATE="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}"
        PYTHONPATH=src ./run-pylint --rcfile=pylint.conf \
            --msg-template=\"$MSG_TEMPLATE\" \
            src plugins
        echo
        echo '---- pycodestyle ----'
        pycodestyle-3 --config pycodestyle.conf src/FedoraReview plugins
    fi
    exit $status
} 2>&1 ) & > $logfile
testpid=$!
tail -f $logfile --pid=$testpid
wait $testpid

exit $?

# vim: set expandtab ts=4 sw=4:
