#!/usr/bin/make -f

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

# generate documentation unless nodoc requested
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
DOCS = README.html README.txt \
 Xdata/README.html Xdata/README.txt \
 Xdata/CHANGELOG.html Xdata/CHANGELOG.txt
#CHANGELOGS =
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)

%:
	dh $@

%.html: %.md
	cmark-gfm $< > $@

%.txt: %.md
	cmark-gfm --to plaintext $< > $@

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS)

# avoid cleaning unless source is patched
override_dh_auto_clean:
	grep -vq -- Xdata Cargo.toml || dh_auto_clean --buildsystem rust

# install documentation, appending stem to basename for embedded crates
override_dh_installdocs:
	file-rename -- 's,^(X([^/]+)/[^.]+)(.*),$$1_$$2$$3,' $(filter X%,$(DOCS))
	dh_installdocs -- $(filter-out X%,$(DOCS)) $(wildcard $(suffix _%,$(basename $(filter X%,$(DOCS)))))

# TODO: enable if main crate provides a changelog
#override_dh_installchangelogs:
#	dh_installchangelogs -- $(CHANGELOGS)

# declare version for virtually provided embedded crate
override_dh_gencontrol:
	 dh_gencontrol -- \
	 -V'rust:Version:librust-perf-event-data-dev=$(call crate_version,Xdata)' \
	 -V'rust:Version:librust-perf-event-open-sys2-dev=$(call crate_version,perf-event-open-sys)'
