#!/usr/bin/make -f

# See debhelper(7) (uncomment to enable).
# Output every command that modifies files on the build system.
#export DH_VERBOSE = 1


# See FEATURE AREAS in dpkg-buildflags(1).
export DEB_BUILD_MAINT_OPTIONS = hardening=+all

# See ENVIRONMENT in dpkg-buildflags(1).
# Package maintainers to append CFLAGS.
#export DEB_CFLAGS_MAINT_APPEND  = -Wall -pedantic
# Package maintainers to append LDFLAGS.
#export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed


%:
	dh $@

override_dh_auto_configure:
	dh_auto_configure -- -DBUILD_SHARED_LIBS:BOOL=ON -DTD_INSTALL_STATIC_LIBRARIES:BOOL=OFF -DTD_INSTALL_SHARED_LIBRARIES:BOOL=ON -DTD_INSTALL_VERSIONED:BOOL=ON

override_dh_install:
	ls debian/tmp/usr/lib/*/TDLib*/*.so.* | while read lib; do \
	    TDLIB_DIR_ABS=$$(dirname $${lib}); \
	    TDLIB_DIR_REL=$$(basename $${TDLIB_DIR_ABS}) \
	    TDLIB_FILE=$$(basename $${lib}); \
	    cd $${TDLIB_DIR_ABS}/..; \
	    ln -s $${TDLIB_DIR_REL}/$${TDLIB_FILE} ./; \
	    cd -; \
	done
	dh_install

override_dh_auto_clean:
	dh_auto_clean
	rm -rf $(CURDIR)/td/generate/auto
	rm -rf $(CURDIR)/tdutils/generate/auto

include /usr/share/dpkg/pkg-info.mk

PKD   = $(word 1,$(abspath $(dir $(MAKEFILE_LIST))))
PKG   = $(DEB_SOURCE)
UVER  = $(shell echo $(DEB_VERSION) | cut -d "-" -f1)
DTYPE = +dfsg
VER  ?= $(subst $(DTYPE),,$(UVER))

UURL = https://github.com/tdlib/td.git
UREV = $(shell echo $(VER) | cut -d"." -f4)

## http://wiki.debian.org/onlyjob/get-orig-source
.PHONY: get-orig-source
get-orig-source: $(PKG)_$(VER)$(DTYPE).orig.tar.xz $(info I: $(PKG)_$(VER)$(DTYPE))
	@

$(PKG)_$(VER)$(DTYPE).orig.tar.xz: $(info I: GIT Revision=$(UREV))
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))
	@echo "# Downloading..."
	git clone $(UURL) $(PKG)-$(VER) \
	   || $(RM) -r $(PKG)-$(VER)
	cd $(PKG)-$(VER) \
	   && git checkout "$(UREV)" \
	   && ( echo "# Generating ChangeLog..." \
	      ; git --no-pager log --format="%ai %aN (%h) %n%n%x09*%w(68,0,10) %s%n" > ChangeLog \
	      ; touch -d "$$(git log -1 --format='%ci')" ChangeLog) \
	   && echo "# Setting times..." \
	   && for F in $$(git ls-tree -r --name-only HEAD); do touch --no-dereference -d "$$(git log -1 --format="%ai" -- $$F)" "$$F"; done \
	   && echo "# Cleaning-up..." \
	   && rm -rf \
	        sqlite \
	        example/android \
	        example/ios \
	        example/swift \
	        example/uwp \
	   && $(RM) -r .git .git* \
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | sort \
	   | XZ_OPT="-6v" tar -caf "../$(PKG)_$(VER)$(DTYPE).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
	   && $(RM) -r "$(PKG)-$(VER)"
