#!/bin/bash
set -e

pkg=orthanc-webviewer

# FIXME: How to obtain the upstream version of the package inside autopkgtest
ver=2.8

# FIXME: How to specify any CPP in autopkgtest
CPP=g++

if [ "${AUTOPKGTEST_TMP}" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf ${AUTOPKGTEST_TMP}" 0 INT QUIT ABRT PIPE TERM
fi

mkdir -p "${AUTOPKGTEST_TMP}"/UnitTestsSources
cp -a /usr/share/doc/${pkg}/examples/* "${AUTOPKGTEST_TMP}"/UnitTestsSources
mkdir -p "${AUTOPKGTEST_TMP}"/Resources/Orthanc
ln -s /usr/share/doc/orthanc/OrthancPluginSamples/Common "${AUTOPKGTEST_TMP}"/Resources/Orthanc/Plugins

cd "${AUTOPKGTEST_TMP}"
find . -name "*.gz" -exec gunzip \{\} \;
cd UnitTestsSources

sed -i 's#../Plugin/##' UnitTestsMain.cpp

for cpp in $(find . -name "*.cpp") ; do
    ${CPP} \
	-DHAS_ORTHANC_EXCEPTION=1 -DORTHANC_PLUGIN_VERSION=\"${ver}\" -DORTHANC_STANDALONE=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE=1 \
	-I/usr/include/jsoncpp -I/usr/include/orthanc-framework -I/usr/src/gtest \
	-g -O2 -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security  -Wdate-time \
	-D_FORTIFY_SOURCE=2 -Wall -Wno-long-long -Wno-variadic-macros -c -o $(basename ${cpp} .cpp).o ${cpp}
done

${CPP} \
	-DHAS_ORTHANC_EXCEPTION=1 -DORTHANC_PLUGIN_VERSION=\"${ver}\" -DORTHANC_STANDALONE=1 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE64_SOURCE=1 \
	-I/usr/include/jsoncpp -I/usr/include/orthanc-framework -I/usr/src/gtest \
	-g -O2 -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security  -Wdate-time \
	-D_FORTIFY_SOURCE=2 -Wall -Wno-long-long -Wno-variadic-macros -o gtest-all.o -c /usr/src/googletest/googletest/src/gtest-all.cc

${CPP} -g -O2 -fstack-protector-strong -fstack-clash-protection -Wformat -Werror=format-security  \
    -Wdate-time -D_FORTIFY_SOURCE=2 -Wall -Wno-long-long -Wno-variadic-macros -Wl,-z,relro -Wl,-z,now -Wl,--as-needed \
    *.o -o UnitTests  -lpthread -lrt -ldl -Wl,-Bstatic \
    -lOrthancFramework -Wl,-Bdynamic -lboost_filesystem -lboost_iostreams -lboost_locale -lboost_regex -lboost_thread \
    -ljsoncpp -lpugixml -luuid -lsqlite3 

# Run upstream executable test
./UnitTests

