#!/usr/bin/make -f
#export DH_VERBOSE=1

DEB_HOST_MULTIARCH ?= $(shell dpkg-architecture -qDEB_HOST_MULTIARCH)

ifeq ($(DEB_STAGE),stage1)
export DH_OPTIONS += -Nruby-semanage -Npython-semanage -Npython3-semanage
else
PYVERSIONS = $(shell pyversions -rv)
PY3VERSIONS = $(shell py3versions -rv)
RUBY_VERSIONS := $(shell dh_ruby --print-supported)
endif

# The build system doesn't use CPPFLAGS, pass them to CFLAGS to enable the
# missing (hardening) flags.
export DEB_CFLAGS_MAINT_APPEND = $(shell dpkg-buildflags --get CPPFLAGS)

%:
ifeq ($(DEB_STAGE),stage1)
	dh $@
else
	dh $@ --with python2 --with ruby --with python3
endif

override_dh_auto_build:
	$(MAKE) all LIBBASE="lib/${DEB_HOST_MULTIARCH}" SELINUXEXECDIR="usr/lib/selinux"

ifneq ($(DEB_STAGE),stage1)
	for version in $(PYVERSIONS); do              \
	  $(MAKE) pywrap PYTHON=python$$version PYLIBS=; \
	done;
	for version in $(PY3VERSIONS); do              \
	  $(MAKE) pywrap PYTHON=python$$version PYLIBS=; \
	done;

	for version in $(RUBY_VERSIONS); do              \
	  $(MAKE) -C src rubywrap RUBY=$$version \
	    RUBYLIBS="$$($$version -e 'puts "-L" + RbConfig::CONFIG["archlibdir"] + " " + RbConfig::CONFIG["LIBRUBYARG_SHARED"]')"; \
	done;
endif

override_dh_auto_install:
	$(MAKE) install DESTDIR="${CURDIR}/debian/tmp" \
	  LIBDIR="${CURDIR}/debian/tmp/usr/lib/${DEB_HOST_MULTIARCH}" \
	  SHLIBDIR="${CURDIR}/debian/tmp/usr/lib/${DEB_HOST_MULTIARCH}" \
	  SELINUXEXECDIR="${CURDIR}/debian/tmp/usr/lib/selinux"

ifneq ($(DEB_STAGE),stage1)
	for version in $(PYVERSIONS); do              \
	  $(MAKE) install-pywrap PYTHON=python$$version  \
	    PYSITEDIR="${CURDIR}/debian/tmp/usr/lib/python$$version/dist-packages"; \
	done;
	for version in $(PY3VERSIONS); do              \
	  $(MAKE) install-pywrap PYTHON=python$$version  \
	    PYSITEDIR="${CURDIR}/debian/tmp/usr/lib/python$$version/dist-packages"; \
	done;

	for version in $(RUBY_VERSIONS); do              \
	  $(MAKE) -C src install-rubywrap RUBY=$$version DESTDIR="${CURDIR}/debian/tmp"; \
	done;
endif

override_dh_auto_clean:
ifneq ($(DEB_STAGE),stage1)
	for version in $(PYVERSIONS); do              \
	  $(MAKE) clean PYTHON=python$$version;  \
	done;
endif

override_dh_install:
	dh_install --list-missing

override_dh_fixperms:
	dh_fixperms
	-chmod -x ${CURDIR}/debian/python-semanage/usr/lib/python*/*-packages/semanage.py
	-chmod -x ${CURDIR}/debian/python3-semanage/usr/lib/python*/*-packages/semanage.py

override_dh_auto_test:
	$(MAKE) test || true
