#!/bin/sh

set -e

cd `dirname $0`/../..
CGE_DIR=${PWD}
DEB_TARGET_MULTIARCH=`dpkg-architecture -q DEB_TARGET_MULTIARCH`
FPCVER=`fpc -iV`
FPCDIR=/usr/lib/${DEB_TARGET_MULTIARCH}/fpc/${FPCVER}
CGE_MAIN_VER=`castle-engine -v | sed -ne 's/castle-engine \([^- ]*\).*/\1/p'`
CGE_INC_DIR=/usr/src/castle-game-engine-${CGE_MAIN_VER}/base
CGE_UNITS_DIR=${FPCDIR}/units/castle-game-engine
PATH=${PATH}:${CGE_DIR}/tools/build-tool
# Command basically copied from tests/compile_console.sh while
# making sure that no unit or object files polute the source tree
castle-engine compile \
	--mode=debug \
	--project=tests \
	--output=${TMP_DIR} \
	--compiler-option=-gh \
	--compiler-option=-dTEXT_RUNNER \
	--compiler-option=-dNO_WINDOW_SYSTEM \
	--compiler-option=-Fu${CGE_UNITS_DIR} \
	--compiler-option=-Fi${CGE_INC_DIR} \
	--compiler-option=@${CGE_DIR}/castle-fpc.cfg

# cd is needed to find the data files
cd tests
# Get tests list
TESTS=`./test_castle_game_engine -l 2> /dev/null | sed -ne 's/  \(TTest.*\)/\1/p'`
# Ignore results for armel until FPC gets fixed.
./test_castle_game_engine -a || test DEB_TARGET_MULTIARCH=arm-linux-gnueabi
FAILED=""
for TEST in ${TESTS}
do
	echo
	echo "CI building ${TEST}"
	CMD="./test_castle_game_engine --suite=${TEST}"
	echo Running: HOME="${AUTOPKGTEST_TMP:-/tmp}" ${CMD}
	if HOME="${AUTOPKGTEST_TMP:-/tmp}" ${CMD}
	then
		SUCCESS="${SUCCESS} ${TEST}"
	else
		FAILED="${FAILED} ${TEST}"
	fi
done

NOT_EXPECTED=""
EXPECTED=""
for TEST in ${FAILED} ; do
    case ${TEST##*/} in
        TTestCastleLevels.TestSetDestroyPlayerAfterLevelLoad) if test ${DEB_TARGET_MULTIARCH} = 'arm-linux-gnueabi' ; then EXPECTED="$EXPECTED ${TEST}" ; fi ;;
        TTestCastleResources.TestResourceFromCode) if test ${DEB_TARGET_MULTIARCH} = 'arm-linux-gnueabi' ; then EXPECTED="$EXPECTED ${TEST}" ; fi ;;
        TTestGame.TestGameData) if test ${DEB_TARGET_MULTIARCH} = 'arm-linux-gnueabi' ; then EXPECTED="$EXPECTED ${TEST}" ; fi ;;
        .) if test ${DEB_TARGET_MULTIARCH} = 'arm-linux-gnueabi' ; then EXPECTED="$EXPECTED ${TEST}" ; fi ;;
        *) NOT_EXPECTED="$NOT_EXPECTED ${TEST}" ;;
    esac
done

if test -n "${SUCCESS}"
then
    echo
    echo "The following files succeeded:"
    for TEST in ${SUCCESS}
	do
        echo ${TEST}
    done
fi

if test -n "${EXPECTED}"
then
    echo
    echo "The following files failed expectedly:"
    for TEST in $EXPECTED
	do
        echo ${TEST}
    done
fi

if test -n "${NOT_EXPECTED}"
then
    echo
    echo "The following files failed unexpectedly:"
    for TEST in ${NOT_EXPECTED}
	do
        echo ${TEST}
    done
    exit 1
fi
