#!/bin/sh
#
# This software is a part of ISAR.
# Copyright (C) 2015-2018 ilbers GmbH

VERBOSE="--show=test"
TIMEOUT=300

# Error codes:
ES_OK=0
ES_FAIL=1
ES_BUG=3

RET=$ES_FAIL

# Get Avocado QEMU tests path
VM_TEST_DIR="$(dirname "$0")/../testsuite/vm_boot_test"

# Go to Isar root
cd "$(dirname "$0")/.."

BUILD_DIR=./build

show_help() {
    echo "This script tests the Isar images for default targets in QEMU."
    echo
    echo "Usage:"
    echo "    $0 [params]"
    echo
    echo "Parameters:"
    echo "    -f,--fast             test reduced set of supported targets."
    echo "    -q, --quiet           do not display boot logs for all the targets."
    echo "                          If test failed for the specific configuration,"
    echo "                          the respective boot log will be printed anyway."
    echo "    -t,--timeout SEC      specify time in seconds to wait before stop QEMU."
    echo "                          The default is: 300"
    echo "    -h, --help            display this message and exit."
    echo
    echo "Exit status:"
    echo " 0  if OK,"
    echo " 1  if test failed,"
    echo " 3  if invalid parameters are passed."
}

# Parse command line to get user configuration
while [ $# -gt 0 ]
do
    key="$1"

    case $key in
    -h|--help)
        show_help
        exit 0
        ;;
    -o|--output)
        # Deprecated option
        shift
        ;;
    -p|--pid-file)
        # Deprecated option
        shift
        ;;
    -f|--fast)
        FAST_BUILD="1"
        ;;
    -q|--quiet)
        VERBOSE=""
        ;;
    -t|--timeout)
        TIMEOUT=$2
        shift
        ;;
    *)
        echo "error: invalid parameter '$key', please try '--help' to get list of supported parameters"
        exit $ES_BUG
        ;;
    esac

    shift
done

TAGS="full"
if [ -n "$FAST_BUILD" ]; then
    TAGS="fast"
fi

# Provide working path
mkdir -p .config/avocado
cat <<EOF > .config/avocado/avocado.conf
[datadir.paths]
base_dir = $BUILD_DIR/
test_dir = $BUILD_DIR/tests
data_dir = $BUILD_DIR/data
logs_dir = $BUILD_DIR/job-results
EOF
export VIRTUAL_ENV="./"

if avocado $VERBOSE run "$VM_TEST_DIR/vm_boot_test.py" -t $TAGS \
    --test-runner=runner --disable-sysinfo \
    -p build_dir="$BUILD_DIR" -p time_to_wait=$TIMEOUT; then
    RET=$ES_OK
fi

exit $RET
