#!/usr/bin/make -f

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

# Upstream strips debug info in its release profile, keep it so that dh_strip
# can move it to the -dbgsym package.
export CARGO_PROFILE_RELEASE_STRIP = none

# The Python bindings are built by maturin through pybuild, it must use the
# Debian registry prepared by dh-rust (same CARGO_HOME as dh-rust's default).
export CARGO_HOME = $(CURDIR)/debian/cargo_home
export CARGO_NET_OFFLINE = true

# The RUSTFLAGS exported by dh-rust take precedence over the crate registry path
# remapping that it writes to the cargo configuration. Remap it explicitly, or
# the build directory leaks into the binaries through dependency source paths.
export RUSTFLAGS += --remap-path-prefix=$(CURDIR)/debian/cargo_registry=/usr/share/cargo/registry
export RUSTFLAGS += --remap-path-prefix=$(CURDIR)=/usr/src/$(DEB_SOURCE)

export PYBUILD_NAME = portablemc
# The CLI is provided by the portablemc package, don't embed it in the module.
export MATURIN_PEP517_ARGS = --no-default-features
# The console script is useless without the embedded CLI, and it would
# conflict with the portablemc package.
export PYBUILD_AFTER_INSTALL = rm -rf {destdir}/usr/bin
export PYBUILD_TEST_PYTEST = 1
# The pytest configuration from pyproject.toml is not used from the pybuild
# build directory, network tests must be deselected explicitly.
export PYBUILD_TEST_ARGS = -m "not network"

# The Python module is built in its own target directory, which is also the
# one scanned for the Built-Using fields of python3-portablemc.
PY_TARGET_DIR = $(CURDIR)/target/python
PYBUILD = --buildsystem=pybuild --sourcedirectory=portablemc-py

%:
	dh $@

execute_after_dh_auto_configure:
	CARGO_TARGET_DIR=$(PY_TARGET_DIR) dh_auto_configure $(PYBUILD)

execute_after_dh_auto_build:
	CARGO_TARGET_DIR=$(PY_TARGET_DIR) dh_auto_build $(PYBUILD)

execute_after_dh_auto_test:
	CARGO_TARGET_DIR=$(PY_TARGET_DIR) dh_auto_test $(PYBUILD)

execute_after_dh_auto_install:
	CARGO_TARGET_DIR=$(PY_TARGET_DIR) dh_auto_install $(PYBUILD)
	/usr/share/dh-rust/bin/dh-rust-built-using $(PY_TARGET_DIR)/release python3-portablemc
# Generate the manual pages with the freshly built binary (not possible when
# cross-building).
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	mkdir -p debian/portablemc/usr/share/man/man1
	debian/portablemc/usr/bin/portablemc gen man debian/portablemc/usr/share/man/man1
endif

execute_after_dh_auto_clean:
	CARGO_TARGET_DIR=$(PY_TARGET_DIR) dh_auto_clean $(PYBUILD)
