#!/usr/bin/make -f
DEB_VERSION=$(shell dpkg-parsechangelog | grep ^Version | cut -f2 -d\ |cut -f1 -d-)
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
TEST_ARCHES=amd64 arm64
PYBUILD_NAME=ubuntu-drivers-common

%:
	dh "$@" --with python3,apport --buildsystem=pybuild

override_dh_auto_test:
ifeq (, $(findstring nocheck, $(DEB_BUILD_OPTIONS)))
  ifeq ($(DEB_HOST_ARCH),$(filter $(DEB_HOST_ARCH), $(TEST_ARCHES)))
	./setup.py egg_info
	PYTHONPATH=. tests/run
	# Run mypy type checking
	mypy UbuntuDrivers/ Quirks/ ubuntu-drivers
	# Run black tests. Same scope as git-hooks/pre-commit, so that a tree
	# which passes the hook also passes the build.
	black --check .
  endif
endif

override_dh_install:
	# -X matches anywhere in the path, so these have to name the gpu-manager
	# files precisely: a bare -Xlib/systemd would also exclude everything
	# under usr/lib/systemd, and a bare -Xsbin everything under usr/sbin.
	dh_install -Xlib/systemd/system/gpu-manager.service \
		-Xsbin/u-d-c-print-pci-ids \
		-Xlib/udev/rules.d

	# on architectures where we build gpu-manager, install the systemd unit,
	# the udev rule, and the script for gpu detection
	if [ -d debian/tmp/lib/systemd ]; then \
		dh_install -p ubuntu-drivers-common lib/systemd; \
		dh_systemd_enable -p ubuntu-drivers-common; \
		dh_install -p ubuntu-drivers-common lib/udev/rules.d; \
		dh_install -p ubuntu-drivers-common sbin; \
	fi

	# build dh_modaliases manpage
	mkdir -p debian/dh-modaliases/usr/share/man/man1
	pod2man -c Debhelper -r "$(DEB_VERSION)" debhelper/dh_modaliases debian/dh-modaliases/usr/share/man/man1/dh_modaliases.1

	# build dh_dmidecode manpage
	mkdir -p debian/dh-dmidecode/usr/share/man/man1
	pod2man -c Debhelper -r "$(DEB_VERSION_EPOCH_UPSTREAM)" debhelper/dh_dmidecode debian/dh-dmidecode/usr/share/man/man1/dh_dmidecode.1

override_dh_installsystemd:
	# com.ubuntu.Drivers is D-Bus activated: enable it so that the
	# dbus-com.ubuntu.Drivers.service alias gets created, but never start it
	# at install time. dbus-daemon starts it on the first method call and it
	# exits again once idle.
	dh_installsystemd --name=ubuntu-drivers --no-start
	dh_installsystemd --name=gpu-manager

override_dh_python3:
	dh_python3 --shebang=/usr/bin/python3

override_dh_clean:
	rm -f share/hybrid/hybrid-detect
	rm -f share/hybrid/gpu-manager
	rm -f quirksreader_test*.txt
	rm -rf build
	rm -rf *.egg-info
	rm -f debian/ubuntu-drivers-common.maintscript
	find $(CURDIR) -name "__pycache__" -exec rm -rf "{}" \;
	rm -f share/hybrid/gpu-manager.o share/hybrid/json-parser/json.o
	dh_clean
