#!/usr/bin/make -f

export DEB_BUILD_MAINT_OPTIONS=hardening=+all

include /usr/share/dpkg/default.mk
include /usr/share/dpkg/buildtools.mk

# The build system builds the Lua module for Lua 5.4 only. We build it for these as well,
# because LuaJIT, which PowerDNS uses, loads modules for Lua 5.1.
LUA_EXTRA_VERSIONS = 5.1 5.3

# The pybuild build system wants to build the Python module for each Python version.
# We must ensure that Autoconf is triggered in a different build directory each time.
# Otherwise, the builder will think the source is already built and re-use the binary.
AUTOTOOLS_ARGS = --buildsystem=autoconf --builddir=.pybuild/autotools-{version}
# However, Lua tests will not run against all the build trees - only the default version.
DEFAULT_BUILDDIR = .pybuild/autotools-$(shell py3versions -dv)

export PYBUILD_SYSTEM=custom
export PYBUILD_CLEAN_ARGS=true
export PYBUILD_CONFIGURE_ARGS=PYTHON={interpreter} dh_auto_configure $(AUTOTOOLS_ARGS) -- \
	--disable-perl --with-systemd
export PYBUILD_BUILD_ARGS=dh_auto_build $(AUTOTOOLS_ARGS)
export PYBUILD_INSTALL_ARGS=dh_auto_install $(AUTOTOOLS_ARGS) --destdir={destdir}; \
	mkdir -p {destdir}/usr/lib/python{version}/dist-packages; \
	mv {destdir}/usr/lib/python3/dist-packages/_location.so {destdir}/usr/lib/python{version}/dist-packages/_location.so
export PYBUILD_TEST_ARGS=dh_auto_test $(AUTOTOOLS_ARGS)

%:
	dh $@ --buildsystem=pybuild

# The module does not link against Lua, which the program that loads it provides,
# so that it does not pull in Lua 5.1 when it is being loaded by LuaJIT
execute_after_dh_auto_build:
	set -e; for version in $(LUA_EXTRA_VERSIONS); do \
		mkdir -p debian/lua$$version; \
		$(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared -fPIC \
			-include $(DEFAULT_BUILDDIR)/config.h -Isrc $$($(PKG_CONFIG) --cflags lua$$version) \
			-o debian/lua$$version/location.so src/lua/*.c -L$(DEFAULT_BUILDDIR)/src/.libs -lloc; \
	done

execute_after_dh_auto_install:
	set -e; for version in $(LUA_EXTRA_VERSIONS); do \
		install -D -m 644 debian/lua$$version/location.so \
			debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/lua/$$version/location.so; \
	done

# Run the tests of the Lua module with all other versions and the Perl module, too,
# unless we cannot run them due to cross-compilation
execute_after_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS) $(DEB_BUILD_PROFILES)))
ifeq ($(DEB_BUILD_ARCH),$(DEB_HOST_ARCH))
	set -e; for version in $(LUA_EXTRA_VERSIONS); do \
		LD_LIBRARY_PATH=$(CURDIR)/$(DEFAULT_BUILDDIR)/src/.libs \
		LUA_CPATH="$(CURDIR)/debian/lua$$version/?.so;;" \
		TEST_DATABASE=$(CURDIR)/data/database.db \
		TEST_SIGNING_KEY=$(CURDIR)/data/signing-key.pem \
			lua$$version $(DEFAULT_BUILDDIR)/tests/lua/main.lua; \
	done
endif
endif

execute_after_dh_auto_clean:
	rm -rf $(foreach version,$(LUA_EXTRA_VERSIONS),debian/lua$(version))
