#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
export DH_VERBOSE=1

# This has to be exported to make some magic below work.
export DH_OPTIONS

DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/buildflags.mk

# parallel support
#NPROC ?= $(shell dh_assistant which-build-system| jq .parallel)
NPROC ?= $(shell nproc)  # for backport

MODULES         = annlib_adaptbx boost_adaptbx cbflib_adaptbx ccp4io_adaptbx cctbx cma_es crys3d fable iotbx libtbx mmtbx scitbx smtbx tbxx wxtbx
MODULES_TODO    = glxtbx rstbx spotfinder
MODULES_FAKE    = ccp4io

%:
	dh $@ --with python3 --buildsystem=pybuild

annlib_adaptbx:
	cp -r debian/annlib_adaptbx annlib_adaptbx

ccp4io_adaptbx:
	cp -r debian/ccp4io_adaptbx ccp4io_adaptbx
	mkdir ccp4io

setup.py : debian/setup.py
	cp -f $< $@

override_dh_auto_clean: setup.py annlib_adaptbx ccp4io_adaptbx
	dh_auto_clean
	find . -name __pycache__ -type d -exec rm -rf {} \;
	rm -f setup.py
	rm -rf annlib_adaptbx
	rm -rf ccp4io ccp4io_adaptbx

override_dh_auto_configure: setup.py annlib_adaptbx ccp4io_adaptbx
	dh_auto_configure
	dh_auto_configure -- -s custom --configure-args="mkdir -p {build_dir}_ && cd {build_dir}_ \
		&& {interpreter} $(CURDIR)/libtbx/configure.py --build=debug --use_environment_flags --enable_cxx11 $(MODULES) $(MODULES_FAKE)"

override_dh_auto_build: setup.py annlib_adaptbx ccp4io_adaptbx
	# build the python modules
	dh_auto_build

	# build the extensions and the libraries
	dh_auto_build -- -s custom --build-args="cd {build_dir}_ && ./bin/libtbx.scons -j $(NPROC)"
	iconv -f ISO-8859-1 -t UTF-8 cctbx/eltbx/covalent_radii.h > covalent_radii.h
	mv covalent_radii.h cctbx/eltbx/covalent_radii.h

	# cp all extensions into the python build directory
	dh_auto_build -- -s custom --build-args="cp -f {build_dir}_/lib/*_ext.so {build_dir}"

override_dh_auto_install: setup.py annlib_adaptbx ccp4io_adaptbx
	dh_auto_install

	# specific installation from the cctbx build directory
	dh_auto_install -- -s custom --install-args="debian/install-cctbx.sh -- --pyver={version} --srcdir=$(CURDIR) --builddir={build_dir}_ --modules='$(MODULES)'"

override_dh_link:
	dh_auto_build -- -s custom --build-args="dh_link -p libcctbx-dev usr/include/cctbx usr/lib/cctbx/python{version}/include"

override_dh_auto_test:
	# DOES NOT WORK, source code must be modified in order to find the expected
	# /usr/share/cctbx libtbx_env file during the build process

# target used to trace the embeded git repository used to build cctbx
# a bunche of modules are missing in the original git repository, so embed them for now
embed:
	# annlib_adaptbx
	-git clone http://github.com/cctbx/annlib_adaptbx annlib_adaptbx
	rm -rf annlib_adaptbx/.git*

	# cpp4io_adaptbx
	-git clone http://github.com/cctbx/ccp4io_adaptbx ccp4io_adaptbx
	rm -rf ccp4io_adaptbx/.git*


.PHONY: embed
