#!/usr/bin/make -f
# -*- makefile -*-
include /usr/share/dpkg/default.mk

# Do not split first WebRTC thread. This does not matter in Telegram Desktop
# and it seems to not lead to crashes or race conditions. See: https://bugs.debian.org/982556
export DEB_CPPFLAGS_MAINT_APPEND = -DNO_MAIN_THREAD_WRAPPING

%:
	dh $@

TEMP_DIR = debian/tmp
INSTALL_DIR = debian/libtgowt-dev
INCLUDE_DIR = $(INSTALL_DIR)/usr/include/tg_owt

# Do not build the library as shared. That's not supported by upstream and too
# difficult to guarantee binary compatibility of C++ code.
EXTRA_CMAKE_VARIABLES += BUILD_SHARED_LIBS=OFF TG_OWT_USE_PROTOBUF=ON

ifeq ($(DEB_HOST_ARCH_CPU),i386)
# Do not force SSE2 extension. Rely on checking via cpuid.
EXTRA_CMAKE_VARIABLES += TG_OWT_ARCH_X86_FORCE_SSE=OFF
endif

ifeq ($(DEB_HOST_ARCH),armhf)
# WebRTC provides no runtime NEON checking, forbid unconditionally usage.
EXTRA_CMAKE_VARIABLES += TG_OWT_ARCH_ARMV7_USE_NEON=OFF
endif

override_dh_auto_configure:
	dh_auto_configure -- $(EXTRA_CMAKE_VARIABLES:%=-D%)

execute_after_dh_auto_install:
# Cut non UTF-8 bytes off to silence national-encoding Lintian warning. Regex taken from https://stackoverflow.com/a/1401716/5000805
	find $(INCLUDE_DIR) -type f -print0 | xargs -0 perl -pi -e 's/((?:[\x00-\x7F]|[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}){1,100})|./$$1/g'
# Comment PACKAGE and related macros to fix package-name-defined-in-config-h Lintian warning.
	find $(INCLUDE_DIR) -name config.h -print0 | xargs -0 sed -i '/\<PACKAGE\(_\|\>\)/s!^\s*#\s*define\s\+!//def!'
# Skip empty directories to fix package-contains-empty-directory Lintian info diagnostic.
	find $(INCLUDE_DIR) -empty -type d -delete

# Download and repack original source code by hand because of uscan(1) does not
# support yet recursive cloning Git repositories. The next script additionally
# invokes tar(1) with options to generate reproducible tarball. You can install
# archiver tool from PyPI: https://pypi.org/project/git-archive-all/
.ONESHELL:
get-orig-source:
	@trap 'rm -rf $(TEMP_DIR)' EXIT ; set -e -u -x
	git clone --depth=1 https://github.com/desktop-app/tg_owt $(TEMP_DIR)/libtgowt.git
	git -C $(TEMP_DIR)/libtgowt.git submodule init
	git -C $(TEMP_DIR)/libtgowt.git submodule update --depth=1
	VERSION=`git -C $(TEMP_DIR)/libtgowt.git log -1 --format=0~git%cd.%h --date=format:%Y%m%d`
	MODIFIED=`git -C $(TEMP_DIR)/libtgowt.git log -1 --format=@%ct`
	git-archive-all -C $(TEMP_DIR)/libtgowt.git --prefix=libtgowt-$$VERSION/ $(TEMP_DIR)/libtgowt.tar
	tar -xf $(TEMP_DIR)/libtgowt.tar -C $(TEMP_DIR)
	rm -r $(TEMP_DIR)/libtgowt-$$VERSION/src/third_party/yasm
	tar --owner=root:0 --group=root:0 --mtime=$$MODIFIED -caf ../libtgowt_$$VERSION+ds.orig.tar.xz -C $(TEMP_DIR) libtgowt-$$VERSION
