#!/usr/bin/make -f

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

# SOURCE_DATE_EPOCH set by dh
export DEB_CPPFLAGS_MAINT_APPEND = -Wno-error=date-time -Wno-error=maybe-uninitialized -Wno-error=stringop-overflow

export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# Rust runtime library.  The crate is shipped as rust/flatbuffers/ inside the
# upstream tree, so dh-cargo's cargo buildsystem (which expects the crate to be
# the whole source package) cannot be used.  Instead the cargo wrapper from the
# cargo package is called directly, which makes the build use the system-wide
# crate registry and the reproducible Rust flags.
export DPKG_EXPORT_BUILDFLAGS = 1
include /usr/share/dpkg/architecture.mk
include /usr/share/dpkg/buildflags.mk
include $(wildcard /usr/share/rustc/architecture.mk)

export CFLAGS CXXFLAGS CPPFLAGS LDFLAGS
export DEB_HOST_GNU_TYPE DEB_HOST_RUST_TYPE

RUST_CRATE = flatbuffers
RUST_CRATE_VERSION = $(patsubst %+dfsg,%,$(DEB_VERSION_UPSTREAM))
RUST_CRATE_DIR = rust/$(RUST_CRATE)
RUST_REGISTRY = $(CURDIR)/debian/cargo_registry
CARGO = /usr/share/cargo/bin/cargo

export CARGO_HOME = $(CURDIR)/debian/cargo_home
export DEB_CARGO_CRATE = $(RUST_CRATE)_$(RUST_CRATE_VERSION)

%:
	dh $@ --with python3

override_dh_auto_configure:
	dh_auto_configure -- -DFLATBUFFERS_BUILD_SHAREDLIB=ON -DCMAKE_POSITION_INDEPENDENT_CODE=ON

ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
override_dh_auto_test-arch:
	dh_auto_test --arch
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	cd $(RUST_CRATE_DIR) && \
		$(CARGO) prepare-debian $(RUST_REGISTRY) --link-from-system
	cd $(RUST_CRATE_DIR) && $(CARGO) test
endif
endif

# Python3 build
override_dh_auto_build-indep:
	dh_auto_build --indep
	set -e; cd python && for pv in $(shell py3versions -vr); do \
		VERSION=$(DEB_VERSION_UPSTREAM) python$$pv setup.py build; \
	done

override_dh_auto_install-arch:
	dh_auto_install --arch

# Python3 install.
override_dh_auto_install-indep:
	dh_auto_install --indep
	set -e; \
	cd python && for pv in $(shell py3versions -vr); do \
		VERSION=$(DEB_VERSION_UPSTREAM) python$$pv setup.py install \
			--install-layout=deb --no-compile \
			--root=$(CURDIR)/debian/python3-flatbuffers; \
	done
	find $(CURDIR)/debian/python3-flatbuffers -name 'flatbuffers-*-nspkg.pth' -delete

execute_after_dh_auto_clean:
	-$(RM) -rf python/build/ python/flatbuffers.egg-info/
	-$(RM) -rf $(RUST_CRATE_DIR)/target $(RUST_CRATE_DIR)/Cargo.lock
	-$(RM) -rf debian/cargo_home debian/cargo_registry

