#!/usr/bin/make -f

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

# generate documentation unless nodoc requested
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
DOCS = README.html README.txt
CHANGELOGS = CHANGELOG.html CHANGELOG.txt
MANPAGES = debian/rsass.1
endif

# Fails on i386: <https://github.com/kaj/rsass/issues/182>
TEST_FLAKY = \
 core_functions::math::log::base::one_fuzzy \
 values::calculation::calc::constant::e::equals_max_precision \
 values::calculation::calc::constant::pi::equals_max_precision

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

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

execute_after_dh_auto_install: $(MANPAGES)

# avoid cleaning unless source is patched
override_dh_auto_clean:
	grep -q -- -PRE rsass*/Cargo.toml || dh_auto_clean --buildsystem rust

override_dh_installdocs:
	dh_installdocs --package rsass -- $(DOCS)
	dh_installdocs --remaining-packages --link-doc librust-rsass-dev -- $(DOCS)

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

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

# build manpages
debian/rsass.1: debian/%.1: debian/rsass/usr/bin/%
	mkdir --parents $(dir $@)
	help2man --section 1 --no-info \
		--name "compiles CSS from SCSS files" \
		--output $@ $< \
		|| { $1 --help; false; }
