#!/usr/bin/make -f

# resolve DEB_VERSION_UPSTREAM DEB_DISTRIBUTION
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 by default
ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
export DEB_CFLAGS_MAINT_STRIP=-O2
export DEB_CXXFLAGS_MAINT_STRIP=-O2
endif

# generate manual page 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; }

mainpkg = rudof
cmds = rudof rudof_generate
maincmd = $(firstword $(cmds))
subcmds_rudof = \
 shapemap shex validate shex-validate shacl-validate data \
 node shacl dctap convert compare rdf-config service query

# generate documentation unless nodoc requested
ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS)))
MANPAGES = $(patsubst %,debian/build/%.1,$(cmds))
endif

%:
	dh $@

override_dh_auto_test:
	dh_auto_test --buildsystem rust -- --no-fail-fast
	RUDOF=$(wildcard target/*/*/rudof) prove --verbose debian/tests/*.t

execute_after_dh_auto_install-arch: debian/$(mainpkg)/usr/bin/$(maincmd) $(MANPAGES)
	mkdir --parents debian/build
	$< completion bash > debian/build/bash-completion
	$< completion fish > debian/build/$(maincmd).fish
	$< completion zsh > debian/build/_$(maincmd)

# build manpages
$(patsubst %,debian/build/%.1,$(cmds)): debian/build/%.1: debian/$(mainpkg)/usr/bin/%
	mkdir --parents debian/build
	$(call _help2man,$@,$<)
	set -e; $(foreach x,$(subcmds_$*),\
	 $(call _help2man,$@,$<,$x);)
