#!/usr/bin/make -f

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

export CARGO_HOME = $(CURDIR)/debian/cargo_home
export CARGO_NET_OFFLINE = true

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

# generate cargo-checksum file
_mkchecksum = printf '{"package":"%s","files":{}}\n' \
 $$(sha256sum $(or $2,$(dir $1)Cargo.toml) | grep -Po '^\S+') > $1;

execute_before_dh_auto_configure:
	$(call _mkchecksum,debian/cargo-checksum.json,Cargo.toml)

# preserve upstream Cargo.lock during build, if provided
	[ -f Cargo.lock.orig ] || [ ! -f Cargo.lock ] \
		|| cp Cargo.lock Cargo.lock.orig

execute_after_dh_auto_configure:
	ln --symbolic --force --relative \
		--target-directory=debian/cargo_registry \
		debian/vendorlibs/*

# use and update local Cargo.lock, if available
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	[ ! -f debian/Cargo.lock ] || cp -f debian/Cargo.lock Cargo.lock
	[ ! -f debian/Cargo.lock ] || cargo update
endif

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)

execute_after_dh_auto_clean:
	[ ! -f Cargo.lock.orig ] || mv -f Cargo.lock.orig Cargo.lock

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

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

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

%:
	dh $@ --buildsystem cargo

# custom target unused during official build
get-vendorlibs: CARGO_NET_OFFLINE = false
get-vendorlibs: export CARGO_HOME = $(CURDIR)/debian/cargo_vendor_home
get-vendorlibs:
# preserve upstream Cargo.lock, and reset to use that
	[ -f Cargo.lock.orig ] || cp Cargo.lock Cargo.lock.orig
	cp -f Cargo.lock.orig Cargo.lock

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

# preserve mangled Cargo.lock for use during build
	sed -e '/^checksum / d' Cargo.lock > debian/Cargo.lock
