#!/usr/bin/make -f
# -*- makefile -*-

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1
PKD   = $(abspath $(dir $(MAKEFILE_LIST)))
PKG   = $(word 2,$(shell dpkg-parsechangelog -l$(PKD)/changelog | grep ^Source))
UVER  = $(shell dpkg-parsechangelog -l$(PKD)/changelog | perl -ne 'print $$1 if m{^Version:\s+(?:\d+:)?(\d.*)(?:\-\d+.*)};')
OVER = $(shell echo $(UVER) | perl -ne 'print $$1 if m{(\d.*)(?:~.+)};')
VER  = $(shell echo $(UVER) | perl -ne 'print $$1 if m{(?:\d.*)(?:\+git(.+))};')

export XDG_RUNTIME_DIR=/tmp

%:
	dh $@ --with autoreconf

override_dh_autoreconf:
	dh_autoreconf
	intltoolize --copy --force --automake

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

UURL = git://git.sv.gnu.org/denemo.git
ifeq ($(strip $(VER)),)
GTARGET = release-$(OVER)
else
GTARGET = $(VER)
endif
$(PKG)_$(UVER).orig.tar.gz: $(info I: GIT=$(GTARGET))
	$(if $(wildcard $(PKG)-$(UVER)),$(error $(PKG)-$(UVER) exist, aborting..))
	@echo "# Downloading..."
	git clone $(UURL) $(PKG)-$(UVER) \
	|| $(RM) -r $(PKG)-$(UVER)
	cd $(PKG)-$(UVER) \
	&& git checkout $(GTARGET) \
	&& 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) -r .git .git*
	@echo "# Packing..."
	find -L "$(PKG)-$(UVER)" -xdev -type f -print | sort \
	| tar -caf "$(PKG)_$(UVER).orig.tar.gz" -T- --owner=root --group=root --mode=a+rX \
	&& $(RM) -r "$(PKG)-$(UVER)"
