#!/usr/bin/make -f
# -*- makefile -*-
# Debian build rules for confget, the configuration variable extractor

export PYBUILD_NAME=confget

# Aim for the top, adapt if anything should break on the buildds.
DEB_BUILD_MAINT_OPTIONS=	hardening=+all future=+lfs
export DEB_BUILD_MAINT_OPTIONS

DEB_CFLAGS_MAINT_APPEND=	-pipe -Wall -W -std=c99 -pedantic -Wbad-function-cast \
		-Wcast-align -Wcast-qual -Wchar-subscripts -Winline \
		-Wmissing-prototypes -Wnested-externs -Wpointer-arith \
		-Wredundant-decls -Wshadow -Wstrict-prototypes -Wwrite-strings
ifneq (,$(filter werror,$(DEB_BUILD_OPTIONS)))
	DEB_CFLAGS_MAINT_APPEND+=	-Werror
endif
export DEB_CFLAGS_MAINT_APPEND

export PCRE_CPPFLAGS=-DHAVE_PCRE
export PCRE_LIBS=-lpcre

ifneq (,$(filter confget,$(shell dh_listpackages)))
BUILD_IMPL_C=yes
else
BUILD_IMPL_C=no
endif
ifneq (,$(filter python3-confget,$(shell dh_listpackages)))
BUILD_IMPL_PY=yes
else
BUILD_IMPL_PY=no
endif

ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS) $(DEB_BUILD_PROFILES)))
BUILD_DOC=yes
else
BUILD_DOC=no
endif

D=	${CURDIR}/debian
DTMP=	$D/tmp
PY=	${CURDIR}/python
TESTD=	${CURDIR}/t

override_dh_auto_build:
	@echo 'building C: ${BUILD_IMPL_C}, python: ${BUILD_IMPL_PY}, doc: ${BUILD_DOC}'
ifeq (yes,${BUILD_IMPL_C})
	dh_auto_build -- LFS_CPPFLAGS= LFS_LDFLAGS=
endif
ifeq (yes,${BUILD_IMPL_PY})
	dh_auto_build -D '${PY}' --buildsystem pybuild
endif

override_dh_auto_install:
ifeq (yes,${BUILD_IMPL_C})
ifeq (no,${BUILD_DOC})
	mv -f Makefile Makefile.bak
	sed -e 's/^install:.*/install: all install-bin/' Makefile.bak > Makefile
endif
	dh_auto_install -- DESTDIR=${CURDIR}/debian/confget PREFIX=/usr \
		MANDIR=/usr/share/man/man BINGRP=root MANGRP=root \
		EXAMPLESDIR=/usr/share/doc/confget/examples \
		INSTALL_PROGRAM='install -m 755' \
		INSTALL_SCRIPT='install -m 755' INSTALL_DATA='install -m 644'
ifeq (no,${BUILD_DOC})
	mv -f Makefile.bak Makefile
endif
endif
ifeq (yes,${BUILD_IMPL_PY})
	dh_auto_install -D '${PY}' --buildsystem pybuild
endif

ifeq (,$(filter nocheck,${DEB_BUILD_OPTIONS}))
override_dh_auto_test:
ifeq (yes,${BUILD_IMPL_C})
	dh_auto_test
endif
ifeq (yes,${BUILD_IMPL_PY})
	env PYTHONPATH='${PY}' '$D/tests/tap-python.sh'
	env TESTDIR='${TESTD}' dh_auto_test -D '${PY}' --buildsystem pybuild -- --test-pytest --test-args '${PY}/unit_tests'
endif
endif

override_dh_installchangelogs:
	dh_installchangelogs -X CHANGES
	set -e; for pkg in $$(dh_listpackages); do \
		install -m 644 CHANGES "debian/$$pkg/usr/share/doc/$$pkg/NEWS"; \
	done

override_dh_auto_clean:
	dh_auto_clean
	if dpkg-query -W -f '$${Package}\n' | fgrep -qxe python3-setuptools; then \
		dh_auto_clean -D '${PY}' --buildsystem pybuild; \
	fi
	rm -rf -- '${PY}/.pytest_cache' '${PY}/confget.egg-info'

override_dh_missing:
	dh_missing --fail-missing

%:
	set -e; \
	if dpkg-query -W python3-setuptools > /dev/null 2>&1; then \
		with='--with python3'; \
	else \
		with=''; \
	fi; \
	echo "Running 'dh $@ $$with'"; \
	dh $@ $$with
