#!/usr/bin/make -f

include /usr/share/dpkg/architecture.mk

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

# TODO: try re-enable upstream optimizations
# disabled to test if cause of flaky multi-thread test (see bug#975696)
ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
export DEB_CFLAGS_MAINT_STRIP=-O2
export DEB_CXXFLAGS_MAINT_STRIP=-O2
export DEB_CFLAGS_MAINT_APPEND=-O3
export DEB_CXXFLAGS_MAINT_APPEND=-O3
endif

# resolve supported architectures for arch-varying build-dependencies
# (in maintainer mode only: uses network and messes with control file)
ifneq (,$(DEB_MAINTAINER_MODE))
$(shell sh debian/pkgarchs.sh default-jdk > debian/ARCHS_java)
endif
$(eval ARCHS_java := $(shell cat debian/ARCHS_java))
ifneq (,$(DEB_MAINTAINER_MODE))
clean: debian/control debian/tests/control

debian/control debian/tests/control::
	perl -g -i -p \
		-e 's/^# autogenerated:[^\n]+\n(?: (?:ant|default-jdk) \[|Architecture: )\K[^\]\n]*/$(ARCHS_java)/gm;' \
		$@
endif
ifeq (,$(filter $(DEB_HOST_ARCH), $(ARCHS_java)))
CONFIGURE_ARGS += --disable-java-bindings
endif

%:
	dh $@

execute_before_dh_auto_clean:
	[ ! -f Makefile ] || $(MAKE) maintainer-clean

override_dh_autoreconf:
	dh_autoreconf --as-needed

override_dh_auto_configure:
	dh_auto_configure -- \
		--disable-static \
		--enable-pthreads \
		--with-hunspell-dictdir=/usr/share/hunspell \
		$(CONFIGURE_ARGS)

override_dh_install:
ifneq (,$(filter $(DEB_HOST_ARCH), $(ARCHS_java)))
	mkdir -p debian/liblink-grammar-java/usr/lib/$(DEB_HOST_MULTIARCH)/jni
	mv debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/liblink-grammar-java.so* \
		debian/liblink-grammar-java/usr/lib/$(DEB_HOST_MULTIARCH)/jni
endif
	find debian/ -name "*.la" -delete
	dh_install -Xtests.py
	d-shlibmove --commit \
		--t64 \
		--devunversioned \
		--exclude-la \
		--exclude-a \
		--multiarch \
		--movedev "debian/tmp/usr/include/*" usr/include/ \
		--movedev "debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/*" \
			usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig \
		debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/*.so

override_dh_compress:
	dh_compress --exclude=.py

override_dh_makeshlibs:
	dh_makeshlibs -- -c4