#!/usr/bin/make -f

# Uncomment this to turn on verbose mode.
# export DH_VERBOSE=1
export DPKG_GENSYMBOLS_CHECK_LEVEL=4
export CFLAGS := $(shell dpkg-buildflags --get CFLAGS) $(shell dpkg-buildflags --get CPPFLAGS)
export CXXFLAGS := $(shell dpkg-buildflags --get CXXFLAGS) $(shell dpkg-buildflags --get CPPFLAGS)
export LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) -Wl,--as-needed
export HOME := $(shell realpath .)
export QT_SELECT=qt5

DEB_HOST_MULTI_ARCH ?= $(shell dpkg-architecture -qDEB_BUILD_MULTIARCH)
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

ifneq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	# Cross compiling
	CONFIGURE_OPTS += "CONFIG+=no_docs" "CONFIG+=cross_compile"
endif

# Skip tests on the archs they are known to be flaky  with current configuration
testskip_architectures := armhf powerpc ppc64el s390x

override_dh_auto_configure:
	qmake $(CONFIGURE_OPTS)
	qmake -r CONFIG+=debian_build $(CONFIGURE_OPTS)

%:
	dh $@ --parallel

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	mkdir -p debian/tmp/home/run
	chmod +x tests/xvfb.sh
ifneq (,$(filter $(DEB_HOST_ARCH),$(testskip_architectures)))
	-tests/xvfb.sh dh_auto_test
else
	tests/xvfb.sh dh_auto_test
endif
endif

override_dh_build:
	dh_auto_build --parallel
	dh_auto_build --parallel -- docs

override_dh_install:
ifeq ($(DEB_BUILD_GNU_TYPE),$(DEB_HOST_GNU_TYPE))
	mkdir -p debian/tmp/`qmake -query QT_INSTALL_DOCS`/qch
	mkdir -p debian/tmp/usr/share/ubuntu-ui-toolkit/doc
	cp -r $(CURDIR)/documentation/*qch debian/tmp/`qmake -query QT_INSTALL_DOCS`/qch
else
	# Add empty qmltypes files
	for module in "Components" "Components/Labs" "Components/Styles" "Layouts" "Metrics" "PerformanceMetrics"; \
	do \
		touch debian/tmp/`qmake -query QT_INSTALL_QML`/Ubuntu/$$module/plugins.qmltypes; \
	done
endif
	rm -f debian/tmp/usr/lib/$(DEB_HOST_MULTIARCH)/*.la
	# FIXME: Due to autopilot not being in the archive we ship docs for now
	# sphinx-build -b singlehtml documentation/autopilot-helpers documentation/autopilot-helpers/_build/html
	# sphinx-build -b json documentation/autopilot-helpers documentation/autopilot-helpers/_build/json
	# Drop QML types used to test apicheck only
	rm -f debian/tmp/usr/lib/*/qt5/qml/Extinct/Animals/*
	dh_install --fail-missing
