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

# export DH_VERBOSE = 1

# Return the minimum value of two integer arguments.
min = $(shell echo $$(( $(1) < $(2) ? $(1) : $(2) )))
max = $(shell echo $$(( $(1) > $(2) ? $(1) : $(2) )))

# Number of CPUs to build Qt.
NO_CPUS := $(call max,$(shell nproc),1)

# There can be multiple builds of Qt in parallel.  The following
# should match the maximum number of per-machine workers used in the
# CI.
MAX_PARALLEL_BUILDS := 4

# qtwebengine (aka chromium) takes a ton of memory per build process,
# up to 2.3 GiB.  Cap the number of jobs based on the amount of
# available memory to try to guard against OOM build failures.
AVAILABLE_MEMORY := $(shell free -g | grep -E '^Mem:' | awk '{print $$7}')
MEMORY_REQUIRED_PER_CORE := 2	# in GiB
COMPUTED_JOB_COUNT := \
  $(call max,$(shell echo $$(( $(AVAILABLE_MEMORY) \
                               / $(MEMORY_REQUIRED_PER_CORE) \
                               / $(MAX_PARALLEL_BUILDS) ))),1)
JOB_COUNT = $(call min,$(NO_CPUS),$(COMPUTED_JOB_COUNT))

%:
	dh $@

override_dh_auto_configure:
	# https://bugs.gentoo.org/768261 (Qt 5.15)
	sed -i 's,#include "absl/base/internal/spinlock.h"1,#include "absl/base/internal/spinlock.h"1\n#include <limits>,g' qtwebengine/src/3rdparty/chromium/third_party/abseil-cpp/absl/synchronization/internal/graphcycles.cc
	sed -i 's,#include <stdint.h>,#include <stdint.h>\n#include <limits>,g' qtwebengine/src/3rdparty/chromium/third_party/perfetto/src/trace_processor/containers/string_pool.h
	# else, break build for ubuntu 21.10
	sed -i 's/static const unsigned kSigStackSize = std::max(16384, SIGSTKSZ);/static const size_t kSigStackSize = std::max(size_t(16384), size_t(SIGSTKSZ));/g' qtwebengine/src/3rdparty/chromium/third_party/breakpad/breakpad/src/client/linux/handler/exception_handler.cc
	# https://bugreports.qt.io/browse/QTBUG-93452 (Qt 5.15)
	sed -i 's,#  include <utility>,#  include <utility>\n#  include <limits>,g' qtbase/src/corelib/global/qglobal.h
	sed -i 's,#include <string.h>,#include <string.h>\n#include <limits>,g' qtbase/src/corelib/global/qendian.h
	cat qtbase/src/corelib/global/qendian.h
	sed -i 's,#include <string.h>,#include <string.h>\n#include <limits>,g' qtbase/src/corelib/global/qfloat16.h
	sed -i 's,#include <QtCore/qbytearray.h>,#include <QtCore/qbytearray.h>\n#include <limits>,g' qtbase/src/corelib/text/qbytearraymatcher.h
	./configure \
	  -opensource \
	  -confirm-license \
	  -nomake examples \
	  -nomake tests \
	  -prefix "${QT_JAMI_PREFIX}"
	sed -i 's,bin/python,bin/env python3,g' qtbase/mkspecs/features/uikit/devices.py

override_dh_auto_build:
	@echo Building Qt using $(JOB_COUNT) parallel jobs
	$(MAKE) -j$(JOB_COUNT) V=1 NINJAFLAGS="-j$(JOB_COUNT)"

override_dh_auto_install:
	dh_auto_install -Smakefile -- INSTALL_ROOT=$(CURDIR)/debian/tmp/
