#!/usr/bin/make -f

# resolve DEB_DISTRIBUTION
include /usr/share/dpkg/pkg-info.mk

# resolve DEB_HOST_RUST_TYPE CARGO_HOME
# ...and transitively DEB_HOST_GNU_TYPE
include /usr/share/rustc/architecture.mk

# resolve if release is experimental
DEB_SUITE_EXP = $(filter experimental% UNRELEASED,$(DEB_DISTRIBUTION))

# resolve crate version
# * get topmost version except prerelease suffix
#   from Cargo.toml file in dir passed as argument
# * source package version if matching upstream part modulo prerelease
# * otherwise append source package version
crate_version = \
 $(shell perl -n \
 -E '/version\W+\K\d+\.\d+\.\d+/ ' \
 -E 'and say "$(DEB_VERSION_UPSTREAM)" =~ /^\Q$$&\E(?:~[a-z]+\d*)?$$/ \
 ? "$(DEB_VERSION)" \
 : "$$&+$(DEB_VERSION_UPSTREAM_REVISION)" and exit' \
 $1/Cargo.toml)

# enable custom execution of cargo wrapper
export DEB_HOST_GNU_TYPE DEB_HOST_RUST_TYPE CARGO_HOME

# reduce risk of out-of-memory issues during build for weak arches
ifneq (,$(filter $(DEB_HOST_ARCH),armel armhf i386 mipsel riscv64))
export RUSTFLAGS += -C embed-bitcode=no -C lto=no -C linker-plugin-lto=no
endif

TEST_BROKEN += \
 codec::prost::tests::encode_too_big \
 max_message_send_size \
 skip_debug

%:
	dh $@

execute_before_dh_auto_build:
	mkdir --parents tonic-health/src/generated/ tonic-reflection/src/generated/ tonic-types/src/generated/
	CARGO_HOME=debian/cargo_home cargo run --package codegen

override_dh_auto_test:
	$(if $(DEB_SUITE_EXP),\
	 dh_auto_test --buildsystem rust -- --no-fail-fast -- --include-ignored || true,\
	 dh_auto_test --buildsystem rust -- --no-fail-fast -- $(addprefix --skip ,$(TEST_BROKEN)))

# declare version for virtually provided embedded crate
override_dh_gencontrol:
	dh_gencontrol -plibrust-tonic-dev -- \
	 -V'rust:Version:librust-tonic-types-dev=$(call crate_version,tonic-types)'
	dh_gencontrol --remaining-packages
