#!/bin/sh -ex
INSTALL_FROM_CPAN="${INSTALL_FROM_CPAN:-0}"

export OPENQA_LOGFILE=/opt/openqa/openqa-debug.log

run_test() {
    # Allow command line options without quotes
    # shellcheck disable=SC2086
    prove -l ${PROVE_ARGS} "$@" || touch tests_failed
}

prepare_fullstack_test() {
    if [ "$CUSTOM_OS_AUTOINST" ]; then
        cp -rd /opt/os-autoinst /opt/testing_area
        if [ "$CUSTOM_OS_AUTOINST_SKIP_BUILD" ]; then
            return
        fi
    else
        git clone --single-branch --depth 1 https://github.com/os-autoinst/os-autoinst.git ../os-autoinst
    fi

    cd ../os-autoinst
    if [ "$INSTALL_FROM_CPAN" -eq 1 ]; then
        cpanm -M https://cpan.metacpan.org --local-lib=~/perl5 local::lib && cpanm -M https://cpan.metacpan.org -n --installdeps .
    else
        cpanm -n --mirror http://no.where/ --installdeps .
    fi
    cmake -G Ninja -DCMAKE_BUILD_TYPE=Release . && ninja -v symlinks
    cd -
    ([ "$INSTALL_FROM_CPAN" -eq 1 ] && eval "$(perl -I ~/perl5/lib/perl5/ -Mlocal::lib)") || true
}

run_fullstack_test() {
    prepare_fullstack_test

    export PERL5OPT="$PERL5OPT $HARNESS_PERL_SWITCHES"
    if ! prove -l "${PROVE_ARGS}" "$@"; then
        touch tests_failed
        find '/tmp' -path '*/t/full-stack.d/openqa/testresults/*/autoinst-log.txt' \
            -exec echo 'contents of' {} \; -exec cat {} \; 2> /dev/null > '/opt/openqa/autoinst-log.txt'
    fi
}

if [ "$FULLSTACK" = 1 ]; then
    run_fullstack_test t/full-stack.t t/05-scheduler-full.t t/33-developer_mode.t
elif [ "$CHECKSTYLE" = 1 ]; then
    make checkstyle || touch tests_failed
else
    if [ "$UITESTS" = 1 ]; then
        list=$(find ./t/ui -name '*.t' | sort)
    else
        list=$(find ./t/ -name '*.t' -not -path './t/ui/*' | sort)
    fi
    # Allow command line options without quotes
    # shellcheck disable=SC2086
    run_test -r $list
fi

[ -r tests_failed ] && exit 1
if test -n "$TRAVIS"; then
    cp -a assets/cache/* /opt/openqa/assets/cache
fi
