#!/usr/bin/make -f

# resolve DEB_VERSION_UPSTREAM
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

# 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/precious.1
endif

# generate manual pages from output of clap-based Rust binary
#  arguments: 1:MANFILEPATH 2:COMMANDPATH 3:SUBCOMMAND(S)
_help2man = \
 $(eval suffix = $(lastword $(subst ., ,$(1))))\
 $(eval stem = $(patsubst %.$(suffix),%,$(1)))\
 help2man --section $(suffix) --no-info \
 --version-string='$(DEB_VERSION_UPSTREAM)' \
 --name $(shell $(2) $(3) --help | head --lines=1 | xargs -0 shell-quote --) \
 --output '$(stem)$(if $(3),-$(subst $() ,-,$(strip $(3)))).$(suffix)' \
 '$(2)$(if $(3), $(3))' \
 || { $(2) $(3) --help; false; }

# 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 $@

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

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

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS)

execute_after_dh_auto_install-arch: $(MANPAGES)

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

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

# build manpages
debian/precious.1: debian/%.1: debian/precious/usr/bin/%
	$(call _help2man,$@,$<)
	set -e; $(foreach x,lint tidy config,\
	 $(call _help2man,$@,$<,$x);)

# custom target unused during official build
get-vendorlibs:
# preserve and use pristine Cargo.lock
	[ -f Cargo.lock.orig ] || cp Cargo.lock Cargo.lock.orig
	cp -f Cargo.lock.orig Cargo.lock

# modernize crates
	cargo update

# preserve needed crates
	cargo vendor --versioned-dirs debian/vendorlibs~
	rm -rf debian/vendorlibs
	mkdir debian/vendorlibs
	cd debian/vendorlibs~ && mv --target-directory=../vendorlibs $(VENDORLIBS)

# mangle to avoid windows-only crates
	perl -gpi \
		-e 's/\[target\W+cfg\(windows\b[^\n]*(\n[^\[\n][^\n]*)*//g;' \
		debian/vendorlibs/comfy-table-7.1.1/Cargo.toml

# strip checksums for mangled crates
	echo '{"package":"Could not get crate checksum","files":{}}' \
	 | tee $(patsubst %,debian/vendorlibs/%/.cargo-checksum.json,\
		comfy-table-7.1.1 \
	 )

# cleanup
	rm -rf debian/vendorlibs~
	[ ! -f Cargo.lock.orig ] || mv -f Cargo.lock.orig Cargo.lock
