#!/usr/bin/make -f

# DH_VERBOSE := 1

# Enable hardening build flags
export DEB_BUILD_MAINT_OPTIONS=hardening=+all optimize=-lto

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

include /usr/share/dpkg/pkg-info.mk

CXXFLAGS += $(CPPFLAGS)

UPSTREAM_VERSION  = $(shell echo $(DEB_VERSION_UPSTREAM) | sed -e 's/\+.*//')

BUILD_DATE = $(shell LC_ALL=C date -u "+%d %B %Y" -d "@$(SOURCE_DATE_EPOCH)")

MANPAGES := $(wildcard debian/man/*.*.xml)

%:
	dh $@ --with pkgkde_symbolshelper,sphinxdoc

override_dh_clean:
	dh_clean debian/man/*.1

	$(RM) -r doc/html

override_dh_auto_configure:
	dh_auto_configure -- -DCMAKE_BUILD_TYPE=RelWithDebInfo \
	                     -DCMAKE_INSTALL_LIBDIR=lib \
	                     -DBUILD_PLUGIN_DRACO=ON \
	                     -DBUILD_PLUGIN_E57=ON \
	                     -DBUILD_PLUGIN_HDF=ON \
	                     -DBUILD_PLUGIN_I3S=ON \
	                     -DBUILD_PLUGIN_ICEBRIDGE=ON \
	                     -DWITH_COMPLETION=ON

override_dh_auto_build:
	# Create man pages from DocBook XML
	for x in $(MANPAGES) ; do \
	  docbook2x-man --string-param header-3="$(BUILD_DATE)" $$x ; \
	  mv `basename $$x | sed 's/.xml$$//'` `dirname $$x` ; \
	done

	dh_auto_build

	sphinx-build doc/ doc/html/ && ln -s /usr/share/javascript/mathjax doc/html/_static/

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	# Exclude tests:
	# - pgpointcloudtest, requires configured PostgreSQL database
	# - pdal_spatial_reference_test, fails sometimes
	(cd obj-* && ctest --force-new-ctest-process --output-on-failure --exclude-regex "pgpointcloudtest|pdal_spatial_reference_test" || echo "Ignoring test failures")
endif

override_dh_auto_install:
	dh_auto_install

	# Strip RPATH
	chrpath --delete debian/tmp/usr/lib/libpdal_plugin_*.so

	# Move pkg-config file to Multi-Arch path
	mkdir debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)
	mv debian/tmp/usr/lib/pkgconfig debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/

	# Remove empty directories
	rmdir $(CURDIR)/debian/*/usr/include/pdal/filters/private/csf
	rmdir $(CURDIR)/debian/*/usr/include/pdal/filters/private/miniball

override_dh_makeshlibs:
	dh_makeshlibs -- -v$(UPSTREAM_VERSION) -c0
