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

# Uncomment this to turn on verbose mode.
#export DH_VERBOSE=1

MANPAGE := debian/git2cl.1
$(MANPAGE):
	perldoc -o checker git2cl
	pod2man -s1 --stderr --utf8 git2cl $(MANPAGE)
	## pod2man may produce empty file so until #659939 is fixed
	## the following is needed to abort on empty file:
	[ -s "$(MANPAGE)" ]

%:
	dh $@

override_dh_clean:
	dh_clean $(MANPAGE)

override_dh_auto_build: $(MANPAGE)

AUX  = $(subst -, ,$(subst :, ,$(DEB_VERSION)))
PKG  = $(word 2, $(AUX))
VER  = $(word 3, $(AUX))

## get-orig-source
GDATE = $(shell date --rfc-3339=seconds --date='TZ="UTC" $(shell echo $(VER) | perl -ne 'print "$$1-$$2-$$3" if m/\+git(\d{4})(\d{2})(\d{2})/')')
.PHONY: get-orig-source
get-orig-source: $(PKG)_$(VER).orig.tar.xz
	@

$(PKG)_$(VER).orig.tar.xz:
	@echo "# Downloading..."
	git clone http://git.savannah.gnu.org/git/git2cl.git $(PKG)-$(VER) \
        || $(RM) -r $(PKG)-$(VER)
	cd $(PKG)-$(VER) \
        && git reset --hard $$(git rev-list --all -n 1 --before="$(GDATE)") \
        && git checkout master \
        && [ -s ChangeLog ] || ( echo "# Generating ChangeLog..." \
           ; git log --pretty="format:%ad  %aN  <%aE>%n%n%x09* %s%n" --date=short > ChangeLog \
           ; touch -d "$(GDATE)" 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) -rv .git .git* \
        && cd .. && echo "# Packing..." \
        && find -L "$(PKG)-$(VER)" -xdev -type f -print \
        | sort | XZ_OPT="-7v" tar -caf "$(PKG)_$(VER).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
        && $(RM) -r "$(PKG)-$(VER)"
