#!/bin/bash
set -e

pkg=orthanc-dicomweb
upstream_version=1.15

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

#  Create folder for the test sources
mkdir -p "${AUTOPKGTEST_TMP}"/UnitTestsSources
cp -a /usr/share/doc/${pkg}/examples/* "${AUTOPKGTEST_TMP}"/UnitTestsSources

cd "${AUTOPKGTEST_TMP}"

cd UnitTestsSources

# Update relative import
sed -i 's/..\/Resources\/Orthanc\/Plugins\///' DicomWebServers.h Configuration.cpp 

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



# Build target object files for UnitTests
for cpp in $(find . -name "*.cpp") ; do

   ${CPP}  -DHAS_ORTHANC_EXCEPTION=1 -DORTHANC_DICOM_WEB_VERSION=\"${upstream_version}\" -DORTHANC_ENABLE_LOGGING_PLUGIN=1 -DORTHANC_STANDALONE=1 -DOrthancDicomWeb_EXPORTS -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 -Wformat -Werror=format-security -DNDEBUG -Wdate-time -D_FORTIFY_SOURCE=2 -Wall -Wno-long-long \
        -Wno-variadic-macros -c -o O$(basename ${cpp} .cpp).o ${cpp}
    
done

# Build target object file for UnitTests
${CPP}  -DHAS_ORTHANC_EXCEPTION=1 -DORTHANC_DICOM_WEB_VERSION=\"1.15\" -DORTHANC_ENABLE_LOGGING_PLUGIN=1 -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 -Wformat -Werror=format-security -DNDEBUG -Wdate-time -D_FORTIFY_SOURCE=2 -Wall -Wno-long-long \
    -Wno-variadic-macros -c -o gtest-all.cc.o /usr/src/gtest/src/gtest-all.cc

# Linking files for UnitTests executable
${CPP} -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG -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 \
        -ldcmdata -ldcmjpeg -ldcmjpls -lofstd -ldcmimage -lz -lrt -ldl -Wl,-Bstatic -lOrthancFramework -Wl,-Bdynamic -lboost_filesystem -lboost_iostreams -lboost_locale -lboost_regex \
        -lboost_thread -ljsoncpp -lpugixml -luuid -lsqlite3 -ldcmdata -ldcmjpeg -ldcmjpls -lofstd -ldcmimage -lz 


# Execute UnitTests
./UnitTests

