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

%:
	dh $@

TEMP_DIR = debian/tmp
INSTALL_DIR = debian/libtgowt-dev
INCLUDE_DIR = $(INSTALL_DIR)/usr/include/tg_owt
FILES_EXCLUDED = src/third_party/abseil-cpp src/third_party/rnnoise src/third_party/yasm

# We do build the static library which is advised by upstream. It is too
# difficult to guarantee binary compatibility of C++ code, and the library has
# only one dependent, Telegram Desktop client.
EXTRA_CMAKE_VARIABLES += TG_OWT_USE_PROTOBUF=ON TG_OWT_DLOPEN_PIPEWIRE=ON

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'
# Skip empty directories to fix package-contains-empty-directory Lintian info diagnostic.
	find $(INCLUDE_DIR) -empty -type d -delete

# Collect all required packages for linking against the static library.
execute_before_dh_gencontrol:
	find $(INSTALL_DIR)/usr -name '*.cmake' | xargs grep -h -o '[^";]*\.so\>' | sort -u | xargs dpkg -S > debian/libtgowt-dev.deps
	echo static:Depends=$$(awk -F: '{print $$1 ","}' debian/libtgowt-dev.deps) >> debian/libtgowt-dev.substvars
ifeq ($(filter terse,$(DEB_BUILD_OPTIONS)),)
	column -t debian/libtgowt-dev.deps
endif

execute_after_dh_clean:
	$(RM) debian/libtgowt-dev.deps

# 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/
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 update --init --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 $(addprefix $(TEMP_DIR)/libtgowt-$$VERSION/,$(FILES_EXCLUDED))
	tar --sort=name --owner=root:0 --group=root:0 --mtime=$$MODIFIED -caf ../libtgowt_$$VERSION+dfsg.orig.tar.xz -C $(TEMP_DIR) libtgowt-$$VERSION

ifeq ($(MAKECMDGOALS),get-orig-source)
.ONESHELL:
endif
