#!/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

# use local fork of dh-cargo and cargo wrapper
PATH := $(CURDIR)/debian/dh-cargo/bin:$(PATH)
PERL5LIB = $(CURDIR)/debian/dh-cargo/lib
export PATH PERL5LIB

# 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
# * append package version if upstream part and crate version differ
crate_version = \
 $(shell perl -n \
 -E '/version\W+\K[^"]+/ and $$_ = $$& =~ s/-PRE/~pre/r ' \
 -E 'and say $$_ eq "$(DEB_VERSION_UPSTREAM)" ? "$(DEB_VERSION)" : "$$_+$(DEB_VERSION_UPSTREAM_REVISION)" and exit' \
 $1/Cargo.toml)

%:
	dh $@ --buildsystem cargo

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

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

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS)

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

execute_after_dh_auto_install: $(MANPAGES)

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

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

override_dh_gencontrol:
	dh_gencontrol -- \
	 -v'$(call crate_version,rsass-cli)' \
	 -VCrate-rsass:Version='$(call crate_version,rsass)' \
	 -VCrate-rsass-macros:Version='$(call crate_version,rsass-macros)'

# skip clean unpatched source unsupported by dh-cargo wrapper
override_dh_auto_clean:
	grep -q -- -PRE rsass*/Cargo.toml || dh_auto_clean

# 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; }
