#!/bin/bash

set -ex

# Parameters of the Orthanc framework
ORTHANC_MD5=ce5f689e852b01d3672bd3d2f952a5ef
ORTHANC_VERSION=1.7.0
ORTHANC_FILENAME=Orthanc-${ORTHANC_VERSION}

# Determine the absolute path to the directory containing the script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

# Download the Orthanc framework
curl http://orthanc.osimis.io/ThirdPartyDownloads/orthanc-framework/${ORTHANC_FILENAME}.tar.gz > /tmp/${ORTHANC_FILENAME}.tar.gz

# Verify the download
ACTUAL_MD5=`md5sum /tmp/${ORTHANC_FILENAME}.tar.gz | cut -d ' ' -f 1`
if [ "${ACTUAL_MD5}" != "${ORTHANC_MD5}" ]; then
    echo "Bad MD5 checksum"
    exit -1
fi

# Uncompress the Orthanc framework
( cd /tmp ; rm -rf /tmp/${ORTHANC_FILENAME} && tar xvf /tmp/${ORTHANC_FILENAME}.tar.gz )

# Possibly remove the files copied from another invocation of this script
rm -rf ${DIR}/${ORTHANC_FILENAME}


# Copy the required files from the Orthanc framework next to this script
SOURCE=/tmp/${ORTHANC_FILENAME}
TARGET=${DIR}/${ORTHANC_FILENAME}

mkdir -p ${TARGET}/Resources/ThirdParty
mkdir -p ${TARGET}/Plugins/Samples/Common

cp ${SOURCE}/Plugins/Samples/Common/OrthancPluginCppWrapper.cpp ${TARGET}/Plugins/Samples/Common
cp ${SOURCE}/Plugins/Samples/Common/OrthancPluginCppWrapper.h ${TARGET}/Plugins/Samples/Common
cp ${SOURCE}/Plugins/Samples/Common/OrthancPluginException.h ${TARGET}/Plugins/Samples/Common
cp ${SOURCE}/Plugins/Samples/Common/VersionScript.map ${TARGET}/Plugins/Samples/Common

cp -r ${SOURCE}/AUTHORS ${TARGET}
cp -r ${SOURCE}/COPYING ${TARGET}
cp -r ${SOURCE}/Core ${TARGET}
cp -r ${SOURCE}/NEWS ${TARGET}
cp -r ${SOURCE}/OrthancServer ${TARGET}
cp -r ${SOURCE}/README ${TARGET}
cp -r ${SOURCE}/Resources/CMake ${TARGET}/Resources
cp -r ${SOURCE}/Resources/EmbedResources.py ${TARGET}/Resources
cp -r ${SOURCE}/Resources/ThirdParty/base64 ${TARGET}/Resources/ThirdParty
cp -r ${SOURCE}/Resources/ThirdParty/md5 ${TARGET}/Resources/ThirdParty
cp -r ${SOURCE}/Resources/ThirdParty/minizip ${TARGET}/Resources/ThirdParty
