#!/usr/bin/make -f

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
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
DOCS = README.html README.txt
CHANGELOGS = CHANGELOG.html CHANGELOG.txt
MANPAGES = tspin.1
endif

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

comma = ,
_mangle = perl -gpi \
 -e 's/$(1)\W+version = "\K\Q$(subst |,$(comma),$(2))"/$(subst |,$(comma),$(3))"/g;' \
 $(patsubst %,debian/vendorlibs/%/Cargo.toml,$(4))

%:
	dh $@

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

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

execute_after_dh_auto_build: $(DOCS) $(CHANGELOGS)

execute_after_dh_auto_install: $(MANPAGES)
	debian/tailspin/usr/bin/tspin --hidden-generate-shell-completions bash > completion.bash
	debian/tailspin/usr/bin/tspin --hidden-generate-shell-completions zsh > _tspin

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

override_dh_installchangelogs:
	dh_installchangelogs -- $(CHANGELOGS)

# generate manpage
tspin.1: %.1: debian/tailspin/usr/bin/%
	help2man --section 1 --no-info \
		--name "log file highlighter and a drop-in replacement for tail -f" \
		--output $@ $< \
		|| { $< --help; false; }

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

# tolerate binary files in preserved code
	find debian/vendorlibs -type f ! -size 0 | perl -lne 'print if -B' \
	 > debian/source/include-binaries

# accept older crates
	$(call _mangle,nu-ansi-term,0.50.1,0.50.0,inlet_manifold-0.1.2)
	$(call _mangle,regex,1.11.0,1.10.6,inlet_manifold-0.1.2)

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

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