#!/bin/bash

set -v

source "$HOME/miniconda/etc/profile.d/conda.sh"
conda activate odil

export WORKSPACE=${WORKSPACE:?}
export BUILD_DIR="${WORKSPACE}/${BUILD_DIR:-build}"
export INSTALL_DIR="${WORKSPACE}/${INSTALL_DIR:-install}"

PYTHON=$(awk -F= '$0 ~ /^PYTHON_EXECUTABLE:/ { print $2 }' ${BUILD_DIR}/CMakeCache.txt)

export LD_LIBRARY_PATH=${INSTALL_DIR}/lib
export PYTHONPATH=${INSTALL_DIR}/$(${PYTHON} -c "from distutils.sysconfig import *; print(get_python_lib(True, prefix=''))")

export ODIL_OWN_AET=LOCAL
export ODIL_PEER_HOST_NAME=127.0.0.1
export ODIL_PEER_PORT=11112
export ODIL_PEER_AET=REMOTE
export PATH=${WORKSPACE}/tests/tools:${PATH}

cd "${WORKSPACE}/tests/data"
dcmqridx ./ dataset.dcm
dcmqrscp -ll error -c dcmqrscp.config 11112 &
sleep 1

cd "${BUILD_DIR}"

ctest --output-on-failure
R1=$?

${PYTHON} -m unittest discover -s ${WORKSPACE}/tests/wrappers/
R2=$?

kill %1
cd "${WORKSPACE}/tests/data"
rm -f index.dat RAW_*.dcm

RETURNCODE=$(if test ${R2} -gt ${R1}; then echo ${R2} ; else echo ${R1}; fi)
exit ${RETURNCODE}
