#!/usr/bin/make -f
DH_VERBOSE := 1
ppa:=$(shell sed -n "1s/.*~.*/yes/p" debian/changelog)
ver:=$(shell dpkg-parsechangelog | sed -nr "2s/Version: (.*)-.*/\1/p")
bd :=$(shell dpkg-architecture -qDEB_BUILD_GNU_TYPE)
py :=obj-$(bd)/bindings/swig/python
pyh:=$(shell if [ -f /usr/share/perl5/Debian/Debhelper/Sequence/python2.pm ]; then echo python2; else echo py_support; fi)

WFLAGS   := -Wall -Werror
CFLAGS    = $(shell dpkg-buildflags --get CFLAGS) $(WFLAGS)
CXXFLAGS  = $(shell dpkg-buildflags --get CXXFLAGS) $(WFLAGS)

%:
	dh $@ --with $(pyh)
override_dh_auto_configure:
	dh_auto_configure -Scmake -- \
	-DLIBSWORD_LIBRARY_TYPE="Shared Static" \
	-DLIBSWORD_SOVERSION=9 \
	-DSWORD_GLOBAL_CONF_DIR='/etc' \
	-DCMAKE_BUILD_TYPE=NONE \
	-DSWORD_BUILD_TESTS="Yes" \
	-DSWORD_BINDINGS="Python"
debian/man/%.1: debian/man/%.1.pod
	pod2man --release="SWORD $(ver)" --center "Sword Module Utilities" $< > $@
override_dh_auto_build: $(basename $(wildcard debian/man/*.pod))
	dh_auto_build -Scmake --parallel
override_dh_auto_test:
	$(shell cd tests/testsuite && ./runall.sh 1>&2)
override_dh_auto_install:
	dh_auto_install -Scmake
	# if you do python-build in dh_auto_build, it will be rebuild again *sigh*
	CFLAGS="$(CFLAGS) -Wno-error" dh_auto_configure -Spython_distutils -D$(py)
	CFLAGS="$(CFLAGS) -Wno-error" dh_auto_build -Spython_distutils -D$(py)
	CFLAGS="$(CFLAGS) -Wno-error" dh_auto_install -Spython_distutils -D$(py)
override_dh_install:
	chrpath -d debian/tmp/usr/bin/* debian/tmp/usr/lib/*so*
	dh_install --list-missing
	# Fixes FTBFS if running binary-arch target only
	-chmod -x debian/libsword-common/usr/share/sword/locales.d/*
override_dh_strip:
	dh_strip --dbg-package=libsword-dbg
ifeq (,$(findstring nostrip,$(DEB_BUILD_OPTIONS)))
	# lintian: python-debug-in-wrong-location, for some value of dh_strip
	# & pysupport or dh_python2
	# need to move if using pysupport, no need to move if using dh_python2
	-mv debian/libsword-dbg/usr/lib/debug/usr/lib/pyshared \
		debian/libsword-dbg/usr/lib/debug/usr/lib/pymodules
	dh_installdirs -p python-sword-dbg usr/lib/debug/usr/lib
	mv debian/libsword-dbg/usr/lib/debug/usr/lib/py* \
	        debian/python-sword-dbg/usr/lib/debug/usr/lib
endif

override_dh_makeshlibs:
	dh_makeshlibs -V
override_dh_clean:
	dh_clean $(patsubst %.pod, %, $(wildcard debian/man/*.pod))

MAKEFILE = $(firstword $(MAKEFILE_LIST))
SOURCE_DIR = $(dir $(MAKEFILE))/..
get-orig-source:
	chmod +x $(SOURCE_DIR)/debian/dfsg.sh
	cd $(SOURCE_DIR) && uscan --force-download --rename --destdir .

override_dh_builddeb:
	dh_builddeb $(if $(ppa),-- -Zlzma)
