#!/usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk   # To access the "DEB_VERSION" variable

export UPSTREAM_VERSION := $(shell echo "$(DEB_VERSION)" | cut -d '+' -f 1)
export TARGET_INDEX := libOrthancMySQLIndex.so
export TARGET_STORAGE := libOrthancMySQLStorage.so

export DEB_BUILD_MAINT_OPTIONS := hardening=+all

# Disable assert() checking from upstream project, for best performance
# https://lists.debian.org/debian-med/2018/04/msg00132.html
export DEB_CFLAGS_MAINT_APPEND=-DNDEBUG
export DEB_CXXFLAGS_MAINT_APPEND=-DNDEBUG

MIRROR=$(shell sed -n 's|.* \(http://[a-z./]*\) .*|\1|p' /etc/apt/sources.list | head -n1)
FILENAME=$(shell apt-cache show orthanc | grep Filename | cut -d\  -f2 | head -n1 | sed 's|_[a-z0-9]*.deb|.dsc|')

%:
	dh $@ --builddirectory=Build

CMAKE_EXTRA_FLAGS += \
	-DCMAKE_SKIP_RPATH:BOOL=ON \
	-DSTATIC_BUILD:BOOL=OFF \
	-DUSE_GOOGLE_TEST_DEBIAN_PACKAGE:BOOL=ON \
	-DORTHANC_FRAMEWORK_SOURCE=path \
	-DORTHANC_FRAMEWORK_ROOT=$(CURDIR)/MySQL/ThirdPartyDownloads/orthanc \
	-DDEB_VERSION=$(DEB_VERSION) \
	-DCMAKE_BUILD_TYPE=None  # The build type must be set to None, see #711515

override_dh_auto_configure:
        # Put 3rd party packages where the cmake build system expects them
	mkdir -p MySQL/ThirdPartyDownloads
	( cd MySQL/ThirdPartyDownloads && \
	apt-get source orthanc || HOME=$(CURDIR)/MySQL/ThirdPartyDownloads dget --allow-unauthenticated $(MIRROR)/$(FILENAME) ; mv orthanc-* orthanc )

	mkdir Build
	dh_auto_configure --builddirectory=Build \
			  --sourcedirectory=MySQL \
			  -- $(CMAKE_EXTRA_FLAGS)

override_dh_clean:
	rm -rf MySQL/ThirdPartyDownloads/
	dh_clean

override_dh_auto_install:
	cp Build/${TARGET_INDEX} Build/${TARGET_INDEX}.${UPSTREAM_VERSION}
	cp Build/${TARGET_STORAGE} Build/${TARGET_STORAGE}.${UPSTREAM_VERSION}

	dh_install Build/${TARGET_INDEX}.${UPSTREAM_VERSION} usr/lib/orthanc
	dh_install Build/${TARGET_STORAGE}.${UPSTREAM_VERSION} usr/lib/orthanc

override_dh_link:
	dh_link usr/lib/orthanc/${TARGET_INDEX}.${UPSTREAM_VERSION} usr/share/orthanc/plugins/${TARGET_INDEX}
	dh_link usr/lib/orthanc/${TARGET_STORAGE}.${UPSTREAM_VERSION} usr/share/orthanc/plugins/${TARGET_STORAGE}

override_dh_installchangelogs:
	dh_installchangelogs -k MySQL/NEWS
