#! /usr/bin/make -f

include /usr/share/dpkg/pkg-info.mk

export PYBUILD_NAME=con-duct
export PYBUILD_BEFORE_TEST=chmod +x {dir}/test/data/spawn_children.sh

PY3VER := $(shell py3versions -dv)

INSTALLDIR := $(CURDIR)/debian/con-duct

%:
	dh $@ --with python3 --buildsystem=pybuild

override_dh_installman: build/duct.1
	dh_installman

build/duct.1:
	: # Generate a manpage by running help2man against the installed
	: # `duct` entry point.  In 0.20.x `duct` is a tiny shim that execs
	: # `con-duct run`, so we need PATH/PYTHONPATH pointing at the
	: # dh_auto_install destdir for the exec'd binary and the package
	: # metadata to resolve.  At this point dh_python3 has not yet
	: # consolidated modules into /usr/lib/python3/dist-packages, so we
	: # must use the per-version path matching the default python3.
	mkdir -p build
	PYTHONPATH=$(INSTALLDIR)/usr/lib/python$(PY3VER)/dist-packages \
	PATH=$(INSTALLDIR)/usr/bin:$$PATH \
	    help2man --no-info --no-discard-stderr \
	        -n "lightweight wrapper that collects execution data for a command" \
	        --version-string="duct $(DEB_VERSION_UPSTREAM)" \
	        $(INSTALLDIR)/usr/bin/duct >| build/duct.1
	: # Rewrite the program name from "con-duct run" to "duct" in
	: # synopsis/usage text so the manpage matches the executable users
	: # invoke.  Preserve quoted prose mentions like 'con-duct run' so
	: # sentences explaining both names don't collapse to a tautology.
	: # help2man escapes dashes in troff as \-, so match both forms.
	sed -i \
	    -e "s/'con\\\\-duct run'/'__KEEP_CONDUCT_RUN__'/g" \
	    -e 's/con\\-duct run/duct/g' \
	    -e 's/con-duct run/duct/g' \
	    -e "s/'__KEEP_CONDUCT_RUN__'/'con-duct run'/g" \
	    build/duct.1
	: # Verify that the manpage generated cleanly -- bail out if any
	: # python error or traceback ended up embedded in the troff source.
	! grep -qE 'Traceback|ImportError|ModuleNotFoundError' build/duct.1
