#! /usr/bin/make -f

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

DEB_BUILD_MAINT_OPTIONS := hardening=+all

include /usr/share/dpkg/architecture.mk
libdir := /usr/lib/$(DEB_HOST_MULTIARCH)

include /usr/share/dpkg/buildtools.mk
# for cross compilation
ifneq ($(DEB_HOST_GNU_TYPE),$(DEB_BUILD_GNU_TYPE))
export _PYTHON_SYSCONFIGDATA_NAME=_sysconfigdata__$(DEB_HOST_MULTIARCH)
define ruby_env
  RUBYLIB=$(libdir)/ruby-crossbuild/$$($(1) -e "puts RbConfig::CONFIG['ruby_version']")
endef
else
define ruby_env
endef
endif

include /usr/share/dpkg/buildopts.mk
MAKEFLAGS += $(DEB_BUILD_OPTION_PARALLEL:%=-j%)

DOPACKAGES = $(shell dh_listpackages)

# Use of lstat64 requires this macro.
export DEB_CPPFLAGS_MAINT_APPEND += -D_LARGEFILE64_SOURCE

# Upstream recommends using this flag
DEB_CFLAGS_MAINT_APPEND := -fno-semantic-interposition
## The build system doesn't use CPPFLAGS, pass them to CFLAGS to enable the
## missing (hardening) flags. Also enable Wall and Wextra to spot basic irregularities.
DEB_CFLAGS_MAINT_APPEND += -Wall -Wextra
DPKG_EXPORT_BUILDFLAGS := 1
include /usr/share/dpkg/buildflags.mk
export CFLAGS += $(CPPFLAGS)

ifneq ($(filter python3-selinux,$(DOPACKAGES)),)
PY3VERSIONS = $(shell py3versions -rv)
endif
ifneq ($(filter ruby-selinux,$(DOPACKAGES)),)
RUBY_VERSIONS := $(shell dh_ruby --print-supported)
endif

%:
	@dh $@

## Set up some variables to be passed to the upstream Makefile
extra_make_args = ARCH=$(patsubst i%86,i386,$(DEB_HOST_GNU_CPU))
extra_make_args += USE_PCRE2=y

override_dh_auto_build: $(PY3VERSIONS:%=build-python-%) \
                        $(RUBY_VERSIONS:%=build-ruby-%)
	$(MAKE) all $(extra_make_args)
build-python-%:
	$(MAKE) pywrap $(extra_make_args) PYTHON=python$*
build-ruby-%:
	$(call ruby_env,$*) \
	$(MAKE) rubywrap $(extra_make_args) RUBY=$*

override_dh_auto_install: $(PY3VERSIONS:%=install-python-%) \
                          $(RUBY_VERSIONS:%=install-ruby-%)
	$(MAKE) install $(extra_make_args) DESTDIR="${CURDIR}/debian/tmp" \
	  LIBDIR=$(libdir) \
	  SHLIBDIR=$(libdir)
  # Patch the python installations.
	find "${CURDIR}/debian/tmp" -name direct_url.json -delete
	find "${CURDIR}/debian/tmp" -name RECORD -exec sed -i '/\/direct_url.json,/d' {} +
install-python-%:
	$(MAKE) install-pywrap $(extra_make_args) PYTHON=python$* DESTDIR="${CURDIR}/debian/tmp" DEB_PYTHON_INSTALL_LAYOUT=deb
install-ruby-%:
	$(call ruby_env,$*) \
	$(MAKE) install-rubywrap $(extra_make_args) RUBY=$* DESTDIR="${CURDIR}/debian/tmp"

override_dh_auto_clean: $(PY3VERSIONS:%=clean-python-%) \
                        $(RUBY_VERSIONS:%=clean-ruby-%)
	rm -f utils/getpolicyload
	$(MAKE) distclean $(extra_make_args) PYTHON=true
clean-python-%:
	$(MAKE) clean-pywrap $(extra_make_args) PYTHON=python$*
clean-ruby-%:
	$(call ruby_env,$*) \
	$(MAKE) clean-rubywrap $(extra_make_args) RUBY=$*
