#!/usr/bin/make -f

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

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
export DEB_CXXFLAGS_MAINT_APPEND  = -Wall -pedantic

# trust upstream optimization level unless explicitly disabled
ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
export DEB_CFLAGS_MAINT_STRIP=-O2
export DEB_CXXFLAGS_MAINT_STRIP=-O2
endif

# 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)

TEST_BROKEN = \
 test_blank_collection_object \
 write_to_nquads \
 write_to_turtle \
 write_to_turtle_with_base \
 write_to_turtle_with_options

%:
	dh $@

override_dh_auto_test:
	dh_auto_test --buildsystem rust -- \
	 --no-fail-fast -- $(addprefix --skip ,$(TEST_BROKEN))

# declare version for virtually provided embedded crates
packages = $(patsubst %,librust-%-dev,\
 rdftk-core)
packages_virtual = $(patsubst %,librust-%-dev,\
 rdftk-io rdftk-iri rdftk-names)
override_dh_gencontrol:
	$(eval librust-rdftk-core-dev_version = $(call crate_version,rdftk_core))\
	$(eval librust-rdftk-io-dev_version = $(call crate_version,rdftk_io))\
	$(eval librust-rdftk-iri-dev_version = $(call crate_version,rdftk_iri))\
	$(eval librust-rdftk-names-dev_version = $(call crate_version,rdftk_names))\
	set -e; $(foreach p,$(packages),\
	 dh_gencontrol -p$p -- \
	 -v'$($p_version)' \
	 $(foreach q,$(filter-out $p,$(packages) $(packages_virtual)),\
	 -V'rust:Version:$q=$($q_version)');)
	dh_gencontrol --remaining-packages
