#!/usr/bin/make -f

# DH_VERBOSE := 1

DEBPKGNAME     := $(shell dpkg-parsechangelog | awk '/^Source:/ {print $$2}')

OS := $(shell dpkg-architecture -qDEB_BUILD_ARCH_OS)
CPU := $(shell dpkg-architecture -qDEB_BUILD_GNU_CPU)
BUILDTYPE := $(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
SODIR := $(DEBPKGNAME)/$(BUILDTYPE)/$(DEBPKGNAME)/$(OS)/gcc/$(CPU)

build2vers := $(shell pyversions -sv)
build3vers := $(shell py3versions -sv)

%:
	dh $@ --with python2,python3,javahelper

override_dh_auto_clean:
	if [ -e ngs-sdk/Makefile.config.$(OS).$(CPU)] ; then \
	#    dh_auto_clean --sourcedirectory=$(DEBPKGNAME) ; \
	dh_auto_clean ; \
	fi
	rm -rf ngs-java/$(BUILDTYPE)
	rm -rf ngs-bam/$(BUILDTYPE)
	rm -f ngs-bam/Makefile.config
	rm -f ngs-bam/Makefile.config.install.linux.x86_64.prl
	rm -f ngs-bam/Makefile.config.linux.x86_64
	rm -f ngs-bam/reconfigure

	rm -rf $(DEBPKGNAME)/$(BUILDTYPE)
	rm -rf ngs-python/build

override_dh_auto_configure:
	# # that's no standard configure script lacking support of default options \
	./configure --build=$(BUILDTYPE) --prefix=/usr ;

override_dh_auto_build:
	#dh_auto_build --sourcedirectory=$(DEBPKGNAME)
	dh_auto_build --sourcedirectory=$(DEBPKGNAME)
	# Remove ngs-bam generation, expects ngs-sdk and cannot find a way
	# to specify it
	#cd ngs-bam && LD_LIBRARY_PATH=../$(SODIR)/rel/lib ./configure --build=$(BUILDTYPE) --prefix=/usr --with-ngs-sdk-prefix=../ngs-sdk
	#dh_auto_build --sourcedirectory=ngs-bam
	dh_auto_build --sourcedirectory=ngs-java
	markdown_py -f README.html README.md

override_dh_auto_test:
	make -C $(DEBPKGNAME)/test
	# Tests of Java binding disabled because need external lib ncbi-vdb,
	# not available in Debian at this time
	#CLASSPATH=../$(BUILDTYPE)/ngs-java/jar/ngs-java.jar LD_LIBRARY_PATH=$(SODIR)/rel/lib:$(LD_LIBRARY_PATH) make -C ngs-java/examples
	#CLASSPATH=../$(BUILDTYPE)/ngs-java/jar/ngs-java.jar LD_LIBRARY_PATH=../../$(SODIR)/rel/lib:$(LD_LIBRARY_PATH) make -C ngs-java/examples run_all

override_dh_auto_install:
	d-shlibmove --commit \
		    --multiarch \
		    --devunversioned \
		    --exclude-a \
		    --exclude-la \
		    --movedev "$(SODIR)/rel/lib/*.a*" usr/lib/$(BUILDTYPE) \
		    --movedev "$(SODIR)/rel/ilib/*.a" usr/lib/$(BUILDTYPE) \
		    $(SODIR)/rel/lib/libngs-sdk.so

override_dh_install:
	dh_install -ppython3-ngs
	set -e && for i in $(build3vers); do \
		cd ngs-python ; \
		python$$i ./setup.py install --install-layout=deb --root ../debian/python3-ngs; \
		cd .. ; \
	done
	dh_install -ppython-ngs
	set -e && for i in $(build2vers); do \
		cd ngs-python ; \
		python$$i ./setup.py install --install-layout=deb --root ../debian/python-ngs; \
		cd .. ; \
	done
	find debian -name "*.pyc" -delete
	find debian -type d -name __pycache__ | xargs rm -rf
