#!/usr/bin/make -f
#export DH_VERBOSE=1
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed
DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)
PKD  = $(abspath $(dir $(MAKEFILE_LIST)))
VER := $(shell dpkg-parsechangelog -l$(PKD)/changelog -SVersion | cut -d- -f1)
WEAK_HOSTS := armel armhf mips mipsel
UURL := https://github.com/freeorion/freeorion.git
PKG := freeorion
COMMIT := cab4aa243552328e71de55f45bc11fc189930494
REV := $(shell echo $(COMMIT) | cut -c1-6)

ifneq (,$(findstring $(DEB_HOST_ARCH),$(WEAK_HOSTS)))
	MAX  := 1
	TYPE := MinSizeRel
else
	MAX  := 4
	TYPE := RelWithDebInfo
endif

%:
	dh $@ --parallel --max-parallel=$(MAX) --with python2

override_dh_auto_configure:
	dh_auto_configure -- \
		-DBUILD_DOCUMENTATION=off \
		-DBUILD_TUTORIALS=off \
		-DLIB_SUFFIX=/freeorion \
		-DCMAKE_VERBOSE_MAKEFILE=ON \
		-DCMAKE_BUILD_TYPE=$(TYPE)

override_dh_auto_build-indep:
	## generate 32x32 xpm icon for compatibility reasons
	convert -monitor default/data/art/icons/FO_Icon_32x32.png debian/freeorion.xpm

#workaround for 'dpkg-shlibdeps: error: couldn't find library libGiGi*.so'
override_dh_shlibdeps:
	LD_LIBRARY_PATH="$(CURDIR)/debian/tmp/usr/lib/freeorion/freeorion:$(LD_LIBRARY_PATH)" dh_shlibdeps

override_dh_installchangelogs:
	dh_installchangelogs changelog.txt

override_dh_install:
	dh_install --fail-missing
	find debian -type d -empty -delete -printf 'removed %p\n'
	$(RM) -v debian/freeorion-data/usr/share/games/freeorion/default/LICENSE* \
		debian/freeorion-data/usr/share/games/freeorion/default/COPYING

override_dh_python2:
	dh_python2 -pfreeorion-data /usr/share/games

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

$(PKG)_$(VER).orig.tar.xz:
	@echo "# Cloning upstream git repository..."
	git clone $(UURL) $(PKG)-$(VER)
	@echo "# Clean-up..."
	cd $(PKG)-$(VER) \
	&& git checkout -b debiansource $(COMMIT) \
	&& for F in $$(git ls-tree -r --name-only HEAD); \
	do touch --no-dereference -d "$$(git log -1 --format="%ai" -- "$$F")" "$$F"; done \
	&& $(RM) -r -v \
		msvc2010 \
		Xcode \
		Installer \
		default/*.ttf \
		.git/ \
	&& sed -i 's:FreeOrion_WC_REVISION ???:FreeOrion_WC_REVISION $(REV):' CMakeLists.txt
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | sort \
	| XZ_OPT="-6v" tar -caf "$(PKG)_$(VER).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
	&& $(RM) -r "$(PKG)-$(VER)"



