#!/usr/bin/make -f
PKD = $(abspath $(dir $(MAKEFILE_LIST)))
PKG = $(shell dpkg-parsechangelog -l$(PKD)/changelog -SSource)
VER = $(shell dpkg-parsechangelog -l$(PKD)/changelog -SVersion | cut -d- -f1)

%:
	dh $@ --with autoreconf --parallel

override_dh_auto_configure:
	dh_auto_configure -- PIONEER_DATA_DIR=/usr/share/games/pioneerspacesim --bindir=/usr/games

# tests fail https://github.com/pioneerspacesim/pioneer/issues/3939#issuecomment-284142629
override_dh_auto_test:

override_dh_install:
	dh_install --list-missing

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

## checkout from git (add "git" to Build-Depends)
UURL = git://github.com/pioneerspacesim/pioneer.git
$(PKG)_$(VER).orig.tar.xz: $(info I: $(PKG)_$(VER))
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))
	@echo "# Downloading..."
	git clone --recursive $(UURL) $(PKG)-$(VER) \
	|| $(RM) -r $(PKG)-$(VER)
	cd $(PKG)-$(VER) \
	&& git checkout $(VER) \
	&& [ -s ChangeLog ] || ( echo "# Generating ChangeLog..." \
	   ; git log --pretty="format:%ad  %aN  <%aE>%n%n%x09* %s%n" --date=short > ChangeLog \
	   ; touch -d "$$(git log -1 --format='%ci')" ChangeLog) \
	&& echo "# Setting times..." \
	&& git ls-tree -r --name-only HEAD | while read F ; do touch --no-dereference -d "$$(git log -1 --format="%ai" -- "$$F")" "$$F"; done \
	&& echo "# Cleaning-up..." \
	&& $(RM) -r .git .git* && ( find . -name ".git*" -type d -exec rm -rf {} \; || /bin/true ) \
	&& find . -name ".git*" -type f -delete
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | LC_ALL=C sort \
	| XZ_OPT="-6v" tar -caf "$(PKG)_$(VER).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
	&& $(RM) -r "$(PKG)-$(VER)"
