#!/usr/bin/make -f
#export DH_VERBOSE=1

PKD = $(abspath $(dir $(MAKEFILE_LIST)))
PKG = $(word 2,$(shell dpkg-parsechangelog -l$(PKD)/changelog | grep ^Source))
VER = $(shell dpkg-parsechangelog -l$(PKD)/changelog | grep "^Version:" | sed "s/^Version:\s\+\(\d:\)\?\([^\+\-]\+\).*/\2/g")
COMMIT = $(shell git log -1 --pretty=%h)

%:
	dh $@

UURL = git://github.com/strukturag/libheif.git
DATE = $(shell date --utc +%Y%m%d%H%M%S)
get-head-source:
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting.))
	@echo "# Downloading..."
	git clone $(UURL) $(PKG)-$(VER) \
		|| $(RM) -r $(PKG)-$(VER)
	cd $(PKG)-$(VER) \
	&& echo "# Checking out commit $(COMMIT)..." \
	&& git checkout -q $(COMMIT) \
	&& 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 \
	&& $(RM) -r .git .git*
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | LC_ALL=C sort \
		| XZ_OPT="-6v" tar -caf "$(PKG)_$(VER)+$(DATE)+git$(COMMIT).orig.tar.xz" -T- --transform "s/$(PKG)-$(VER)/$(PKG)_$(VER)+$(DATE)+git$(COMMIT)/g" --owner=root --group=root --mode=a+rX \
	&& $(RM) -r "$(PKG)-$(VER)"
