#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

export DEB_BUILD_HARDENING=1
export DPKG_GENSYMBOLS_CHECK_LEVEL=4

DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)
# Skip tests on the archs they are known to be flaky with current configuration
# Ref.: https://bugs.launchpad.net/ubuntu/+source/mesa/+bug/1585942
testskip_architectures := s390x powerpc

ifneq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS)))
	CONFIGURE_OPTS += -DENABLE_TESTS=OFF
endif

ifneq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	DEB_BUILD_PROFILES += cross
endif

# Add migrations add-on when build on Ubuntu & original name is available.
DH_MIGRATIONS = $(shell command -v dh_migrations >/dev/null 2>&1 && echo "--with migrations")

%:
	dh $@ $(DH_MIGRATIONS)

ifeq ($(shell dpkg-vendor --derives-from Ubuntu && echo yes),yes)
apparmor:
	aa-easyprof -m ./debian/lomiri-messaging-app-apparmor.manifest --no-verify | \
	egrep -v '(# Click packages|CLICK_DIR)' | \
	sed 's/@{APP_PKGNAME}_@{APP_APPNAME}_@{APP_VERSION}/@{APP_PKGNAME}/g' | \
	sed 's,Apps/@{APP_PKGNAME},Apps/lomiri-messaging-app,g' | \
	sed '/dconf.user rw/c\  \/run\/user\/\[0-9\]*\/dconf\/user rw,' | \
	sed 's,deny owner .*dconf/user r,owner @\{HOME\}/.config/dconf/user r,g' | \
	egrep -v 'deny /run/udev/data/\*\* r,' | \
	sed 's#^}$$#\n  /sys/class/ r,\n  /sys/class/input/ r,\n  /run/udev/data/** r,\n}#g' | \
	egrep -v '^\s*deny /dev/ r,\s*$$' | \
	sed 's#^\(\s*\)deny\(\s\+/{run,dev}/shm/pulse-shm\*\s\+w,\).*$$#\1owner\2#g' | \
	sed 's#^}$$#\n  /dev/dri/ r,\n  /sys/devices/pci[0-9]*/**/config r,\n}#g' \
	> ./debian/usr.bin.lomiri-messaging-app
	(head -n -2 ./debian/usr.bin.lomiri-messaging-app; cat ./debian/lomiri-messaging-app-apparmor.additions; \
	echo } ) > ./debian/usr.bin.lomiri-messaging-app2
	mv ./debian/usr.bin.lomiri-messaging-app2 ./debian/usr.bin.lomiri-messaging-app
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	apparmor_parser -QTK ./debian/usr.bin.lomiri-messaging-app
endif

execute_after_dh_install: apparmor
	dh_install -p lomiri-messaging-app debian/usr.bin.lomiri-messaging-app etc/apparmor.d
endif

override_dh_missing:
	dh_missing --fail-missing

override_dh_installdeb:
	dh_apparmor --profile-name=usr.bin.lomiri-messaging-app -plomiri-messaging-app
	dh_installdeb

override_dh_auto_configure:
	dh_auto_configure -- \
		$(CONFIGURE_OPTS)

override_dh_auto_test:
	# python3 -m flake8 tests/autopilot/lomiri_messaging_app/
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
ifneq (,$(filter $(DEB_HOST_ARCH),$(testskip_architectures)))
	-dh_auto_test
else
	dh_auto_test
endif
endif

override_dh_translations:
	# Override dh_translations to work around http://pad.lv/1183262.
	# Unfortunately, the default build directory is not exposed
	# (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=601774).
	$(MAKE) -C obj-$(DEB_HOST_GNU_TYPE) lomiri-messaging-app.pot
