#!/usr/bin/make -f

# generate documentation unless nodoc requested
DOCS_stem = README $(basename $(wildcard docs/*.md))
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
DOCS = $(addsuffix .html,$(DOCS_stem)) $(addsuffix .txt,$(DOCS_stem))
CHANGELOGS = Changes.html Changes.txt
MANPAGES = debian/build/precious.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

# resolve all direct entries in first "package..." section in TODO
VENDORLIBS = $(shell perl -nE \
 '/^(?:\s{2}[*]\s*(?:(package)|(\S+))|\s{4}[*]\s*(\S+))/ or next; \
 $$i++ if $$1; exit if $$i > 1 or $$2; say $$3 if $$3 and $$i;' \
 debian/TODO)

%:
	dh $@ --buildsystem cargo

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

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

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS)

execute_after_dh_auto_install: $(MANPAGES)

override_dh_installdocs:
	dh_installdocs --all -- $(DOCS)

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

# build manpages
debian/build/precious.1: debian/build/%.1: debian/precious/usr/bin/%
	mkdir --parents $(dir $@)
	help2man --section 1 --no-info \
		--name "one code quality tool to rule them all" \
		--output $@ $< \
		|| { $1 --help; false; }

# custom target unused during official build
get-vendorlibs:
# preserve needed crates
	cargo vendor --versioned-dirs debian/vendorlibs~
	rm -rf debian/vendorlibs
	mkdir debian/vendorlibs
	cd debian/vendorlibs~ && mv --target-directory=../vendorlibs $(VENDORLIBS)
