#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS = hardening=+all optimize=+lto

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

# CMake build directory (dh default) holding libmarisa.so.
B := $(CURDIR)/obj-$(DEB_HOST_GNU_TYPE)
# The SWIG bindings are generated and built in a copy inside the build
# directory, so the source tree is never modified and dh_auto_clean
# removes everything.
BINDINGS := obj-$(DEB_HOST_GNU_TYPE)/bindings

%:
	dh $@

# Upstream restricts its install() rules to CONFIGURATIONS Release.
override_dh_auto_configure:
	dh_auto_configure -- \
		-DBUILD_SHARED_LIBS=ON \
		-DCMAKE_BUILD_TYPE=Release
	rm -rf $(BINDINGS)
	cp -a bindings $(BINDINGS)
	# We do not use bindings/python, see https://github.com/s-yata/marisa-trie/issues/55
	$(MAKE) -C $(BINDINGS) swig-perl swig-python3 swig-ruby
	sed -i 's/__version__/$(DEB_VERSION_UPSTREAM)/' $(BINDINGS)/python3/setup.py
	# MakeMaker would install the example scripts as modules.
	rm $(BINDINGS)/perl/benchmark.pl $(BINDINGS)/perl/sample.pl

# The bindings link against libmarisa, so they are configured only after
# the library has been built.
execute_after_dh_auto_build:
	dh_auto_configure --buildsystem=perl_makemaker --sourcedirectory=$(BINDINGS)/perl -- \
		INC=-I$(CURDIR)/include \
		LIBS="-L$(B) -lmarisa"
	dh_auto_build --buildsystem=perl_makemaker --sourcedirectory=$(BINDINGS)/perl -- \
		LD_RUN_PATH=
	CPPFLAGS="$(CPPFLAGS) -I$(CURDIR)/include" LDFLAGS="$(LDFLAGS) -L$(B)" \
		dh_auto_build --buildsystem=pybuild --sourcedirectory=$(BINDINGS)/python3
	# Relative include path: Ruby's own CFLAGS do not remap the build path
	# (the assertion macros in the headers use __FILE__).
	cd $(BINDINGS)/ruby && ruby extconf.rb --vendor \
		--with-opt-include=../../../include --with-opt-lib=$(B)
	$(MAKE) -C $(BINDINGS)/ruby V=1

execute_after_dh_auto_install:
	dh_auto_install --buildsystem=perl_makemaker --sourcedirectory=$(BINDINGS)/perl
	dh_auto_install --buildsystem=pybuild --sourcedirectory=$(BINDINGS)/python3
	$(MAKE) -C $(BINDINGS)/ruby install DESTDIR=$(CURDIR)/debian/tmp

# record minimum ruby version requirement
# see https://bugs.debian.org/1006289
override_dh_gencontrol:
	dh_gencontrol -- \
		-V"ruby:Build-Version=$$(dpkg-query -f='$${Version}' -W ruby)"
