#!/bin/bash

set -u

APP_NAME="cage-gtk-demo"

BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOGDIR="/var/log/redtest/${APP_NAME}"
SUMMARY_TAP="${LOGDIR}/run-redtest.tap"

COMMON_APP="redpesk-images-tester"
COMMON_RUNNER="/usr/libexec/redtest/${COMMON_APP}/run-redtest"
COMMON_LOGDIR="/var/log/redtest/${COMMON_APP}"

GRAPHIC_CHECK="${BASEDIR}/checks/grafic-check.sh"

mkdir -p "${LOGDIR}"

# Remove results from a previous run.
rm -f "${LOGDIR}"/*.tap 2>/dev/null || :

echo "TAP version 13" > "${SUMMARY_TAP}"
echo "1..2" >> "${SUMMARY_TAP}"

echo
echo "*******************************"
echo "Running cage-gtk-demo tests"
echo "*******************************"
echo

#
# 1. cage-gtk-demo graphical test
#

graphic_result=0

if [[ ! -x "${GRAPHIC_CHECK}" ]]; then
    echo "ERROR: ${GRAPHIC_CHECK} not found or not executable"
    graphic_result=1
else
    "${GRAPHIC_CHECK}"
    graphic_result=$?
fi

if [[ ${graphic_result} -eq 0 ]]; then
    echo "ok 1 - cage-gtk-demo graphical test" | tee -a "${SUMMARY_TAP}"
else
    echo "not ok 1 - cage-gtk-demo graphical test" | tee -a "${SUMMARY_TAP}"
fi


#
# 2. Common redpesk image tests
#

echo
echo "************************************"
echo "Running common redpesk image tests"
echo "************************************"
echo

common_result=0

if [[ ! -x "${COMMON_RUNNER}" ]]; then
    echo "ERROR: ${COMMON_RUNNER} not found or not executable"
    common_result=1
else
    # Avoid evaluating TAP files left by a previous run.
    mkdir -p "${COMMON_LOGDIR}"
    rm -f "${COMMON_LOGDIR}"/*.tap 2>/dev/null || :

    "${COMMON_RUNNER}"
    runner_result=$?

    if [[ ${runner_result} -ne 0 ]]; then
        common_result=1
    fi

    #
    # redpesk-images-tester/run-redtest currently always exits with 0,
    # so also inspect the generated TAP files.
    #
    shopt -s nullglob
    common_taps=("${COMMON_LOGDIR}"/*.tap)
    shopt -u nullglob

    if [[ ${#common_taps[@]} -eq 0 ]]; then
        echo "ERROR: redpesk-images-tester generated no TAP result"
        common_result=1
    else
        for tap_file in "${common_taps[@]}"; do
            if grep -q '^not ok ' "${tap_file}"; then
                common_result=1
            fi

            # Keep a copy with the cage-gtk-demo redtest results.
            cp -f "${tap_file}" \
                "${LOGDIR}/${COMMON_APP}-$(basename "${tap_file}")"
        done
    fi
fi

if [[ ${common_result} -eq 0 ]]; then
    echo "ok 2 - redpesk common image tests" | tee -a "${SUMMARY_TAP}"
else
    echo "not ok 2 - redpesk common image tests" | tee -a "${SUMMARY_TAP}"
fi


echo
echo "Redtest results:"
echo "  ${SUMMARY_TAP}"
echo

#
# Test failures are reported through TAP.
# This follows the behaviour of redpesk-images-tester/run-redtest.
#
exit 0
