#!/usr/bin/make -f

export TOX_SITEPACKAGES=true

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

# Strip everything after ~ (e.g. ~dfsg-1) or + (e.g. +20261101)
PROJECT_UPSTREAM_VERSION := $(firstword $(subst +, ,$(subst ~,+,$(DEB_VERSION_UPSTREAM))))
export SETUPTOOLS_SCM_PRETEND_VERSION_FOR_SD_DEBIAN := $(PROJECT_UPSTREAM_VERSION)

# Run test from source tree
export PYBUILD_TEST_PYTEST=1
export PYBUILD_TEST_ARGS=--rootdir={dir} {dir}/src

# Disable pip isolation, index and dependencies resolution in tox
export PIP_NO_BUILD_ISOLATION=0
export PIP_NO_INDEX=1
export PIP_NO_DEPS=1

PYTHON3_DEFAULT := $(shell py3versions -vd)

%:
	dh ${@} --buildsystem=pybuild --with bash-completion

execute_after_dh_auto_clean:
	rm -rf *.egg-info
	rm -rf .tox
	rm -f debian/sd-debian-ansible.bash-completion

execute_before_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	tox -e lint
endif

execute_after_dh_auto_install:
	# Remove tests files
	find debian/sd-debian-ansible/usr/lib/python*/dist-packages/sd_debian -type d -name "tests" -exec rm -rf {} +

execute_before_dh_bash-completion:
	# Generate bash-completions with shtab
	PYTHONPATH=debian/sd-debian-ansible/usr/lib/python$(PYTHON3_DEFAULT)/dist-packages:$(PYTHONPATH) \
	shtab \
		--shell=bash \
		--error-unimportable sd_debian.config.get_parser \
		--prog sd-debian \
	> debian/sd-debian-ansible.bash-completion

execute_after_dh_installman:
	# Generate manpage from argparse
	mkdir -p debian/sd-debian-ansible/usr/share/man/man1

	PYTHONPATH=debian/sd-debian-ansible/usr/lib/python$(PYTHON3_DEFAULT)/dist-packages:$(PYTHONPATH) \
	argparse-manpage \
		--module sd_debian.config \
		--function get_parser \
		--version "$(DEB_VERSION_UPSTREAM)" \
		--description "YAML-driven configuration manager for Debian-based system" \
		--output debian/sd-debian-ansible/usr/share/man/man1/sd-debian.1
