#!/usr/bin/make -f

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

# Keep the older C bridge on stable releases
C_BRIDGE = $(filter $(shell . /etc/os-release; echo $${VERSION_ID:-unstable}),11 12 22.04)
ifeq ($(C_BRIDGE),)
CONFIG_OPTIONS += --enable-pybridge
endif

# riscv is an emulated architecture for now, and too slow to run expensive unit tests
# hppa's threading is absurdly slow (#981127)
SLOW_ARCHES = $(filter $(shell dpkg-architecture -qDEB_BUILD_ARCH),riscv64 hppa)
ifneq ($(SLOW_ARCHES),)
	export COCKPIT_SKIP_SLOW_TESTS=1
endif

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

override_dh_auto_configure:
	dh_auto_configure -- \
		--with-cockpit-user=cockpit-ws \
		--with-cockpit-ws-instance-user=cockpit-wsinstance \
		--with-pamdir=/lib/$(DEB_HOST_MULTIARCH)/security \
		--libexecdir=/usr/lib/cockpit $(CONFIG_OPTIONS)

# HACK: Debian's pip breaks --prefix: https://bugs.debian.org/1035546
# redirect /usr/local to /usr, as merging the trees after install is brittle
execute_before_dh_auto_install:
	mkdir -p debian/tmp/usr; ln -s . debian/tmp/usr/local

# undo the pip hack
execute_after_dh_auto_install:
	rm debian/tmp/usr/local

# avoid trying to start cockpit-motd.service and cockpit-wsinstance-*.socket etc.
override_dh_installsystemd:
	dh_installsystemd -p cockpit-ws cockpit.socket

override_dh_install:
	# Debian/Ubuntu PAM config
	mkdir -p debian/tmp/etc/pam.d
	install -p -m 644 tools/cockpit.debian.pam debian/tmp/etc/pam.d/cockpit

	# don't ship broken branding symlinks
	for d in rhel fedora centos scientific opensuse; do rm -r debian/tmp/usr/share/cockpit/branding/$$d; done
	dpkg-vendor --derives-from ubuntu || rm -r debian/tmp/usr/share/cockpit/branding/ubuntu

	# handled by package maintainer scripts
	rm debian/tmp/etc/motd.d/cockpit debian/tmp/etc/issue.d/cockpit.issue

	# unpackaged modules
	rm -r debian/tmp/usr/share/cockpit/kdump
	rm debian/tmp/usr/share/metainfo/org.cockpit-project.cockpit-kdump.metainfo.xml
	rm -r debian/tmp/usr/share/cockpit/selinux
	rm debian/tmp/usr/share/metainfo/org.cockpit-project.cockpit-selinux.metainfo.xml

	dh_install -Xusr/src/debug
ifeq ($(C_BRIDGE),)
	# we don't need this, it contains full build paths and breaks reproducibility
	rm -r debian/tmp/usr/lib/python*/*-packages/*.dist-info
	dh_install -p cockpit-bridge debian/tmp/usr/lib/python*
endif

	make install-tests DESTDIR=debian/cockpit-tests

execute_after_dh_install-indep:
	# avoid dh_missing failure
ifeq ($(C_BRIDGE),)
	rm -r debian/tmp/usr/lib/python*
endif

# run pytests *after* installation, so that we can make sure that we installed the right files
execute_after_dh_install-arch:
ifeq (, $(findstring nocheck, $(DEB_BUILD_OPTIONS)))
ifeq ($(C_BRIDGE),)
	pytest -vv -k 'not linter and not test_descriptions' -opythonpath=$$(ls -d debian/cockpit-bridge/usr/lib/python3*/dist-packages)
endif
endif
