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

# Rules for building Debian package. Based on the following files:
#  * docs/building-cmake.md
#  * Telegram/gyp/refresh.sh
#  * Telegram/Patches/gyp.diff
# Please recheck this file if they are changed in future versions.

include /usr/share/dpkg/default.mk
OUT = obj-$(DEB_HOST_GNU_TYPE)

ifeq (,$(filter noopt,$(DEB_BUILD_OPTIONS)))
 BUILD_MODE = Release
 ifeq ($(DEB_HOST_ARCH_BITS), 32)
  # Less debugging information to avoid running out of address space when
  # linking on architectures with reduced amount of memory.
  DEB_CXXFLAGS_MAINT_APPEND += -g1
 endif
 EXTRA_MACROS += RPL_CONSUMER_TYPE_ERASED_ALWAYS
else
 BUILD_MODE = Debug
endif

# Use custom id and hash for Telegram API.
TELEGRAM_API_ID = 50322
TELEGRAM_API_HASH = 9ff1a639196c0779c86dd661af8522ba

GYPFLAGS += \
	--format=cmake \
	--depth=Telegram/gyp \
	--generator-output=../.. \
	-Dapi_id=$(TELEGRAM_API_ID) \
	-Dapi_hash=$(TELEGRAM_API_HASH) \
	-Duse_packed_resources \
	-Goutput_dir=$(OUT) \
	-Gconfig=$(BUILD_MODE)

EXTRA_MACROS += \
	TDESKTOP_DISABLE_AUTOUPDATE \
	TDESKTOP_DISABLE_CRASH_REPORTS \
	TDESKTOP_DISABLE_REGISTER_CUSTOM_SCHEME

# Workarounds for non-Linux systems
ifneq ($(DEB_HOST_ARCH_OS),linux)
 EXTRA_MACROS += Q_OS_LINUX  # brilliant bluff :)
 GYPFLAGS += --no-parallel  # see bugs.debian.org/799356
endif

CPPLIBS_PACKAGES = libmapbox-variant-dev libmsgsl-dev librange-v3-dev libtgvoip-dev
EXTRA_SUBSTVARS += \
	cpplibs:Built-Using=$(shell dpkg-query -Wf '$${source:Package}(=$${Version}),' $(CPPLIBS_PACKAGES))

export DEB_BUILD_MAINT_OPTIONS = hardening=+all
export DEB_CPPFLAGS_MAINT_APPEND += $(EXTRA_MACROS:%=-D%)
export DEB_CXXFLAGS_MAINT_APPEND += -Werror=invalid-pch
export DEB_LDFLAGS_MAINT_APPEND

# A generated CMake config will be placed in the next "source" directory.
%:
	dh $@ --sourcedirectory=$(OUT)/$(BUILD_MODE)

# We use a default source directory as fallback when an user tries to clear a
# clean tree or when the clean target is called twice in a row. In this case,
# debhelper says that the source directory doesn't exist so we omit the
# sourcedirectory parameter.
override_dh_auto_clean:
	dh_auto_clean || dh_auto_clean --sourcedirectory=$(CURDIR)
	rm -f Telegram/gyp/tests/*.test

# We append content of the d/CMakeLists.inj file into the generated
# CMakeLists.txt instead of patching gyp utility.
override_dh_auto_configure:
	gyp $(GYPFLAGS) Telegram/gyp/Telegram.gyp
	sed -i '$$r debian/CMakeLists.inj' $(OUT)/$(BUILD_MODE)/CMakeLists.txt
	dh_auto_configure

override_dh_installchangelogs:
	dh_installchangelogs changelog.txt

override_dh_gencontrol:
	dh_gencontrol -- $(EXTRA_SUBSTVARS:%="-V%")
