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

# From http://wiki.debian.org/onlyjob/get-orig-source

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+.*)};')
DTYPE = +repack1
VER  ?= $(subst $(DTYPE),,$(UVER))

.PHONY: get-orig-source

%:
	dh $@

override_dh_installchangelogs:
	dh_installchangelogs -k

get-orig-source: $(PKG)_$(VER)$(DTYPE).orig.tar.xz
	@

$(PKG)_$(VER)$(DTYPE).orig.tar.xz:
	@echo "# Downloading ..."
	uscan --noconf --verbose --rename --destdir=$(CURDIR) --check-dirname-level=0 --force-download --download-version $(VER) $(PKD)
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))

	@echo "# Extracting ..."
	mkdir $(PKG)-$(VER) \
	&& tar -xf $(PKG)_$(VER).orig.tar.* --directory $(PKG)-$(VER) --strip-components 1 \
	|| $(RM) -r $(PKG)-$(VER)

	@echo "# Cleaning up ..."
	find $(PKG)-$(VER) -name '*.ttc' -delete
	find $(PKG)-$(VER) -name '*.otf' -delete

	@echo "# Extracing NotoSansCJK.ttc"
	unzip $(PKG)-$(VER)/NotoSansCJK.ttc.zip -d $(PKG)-$(VER)
	rm $(PKG)-$(VER)/NotoSansCJK.ttc.zip

	@echo "# Packing ..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | LC_ALL=C sort \
	| XZ_OPT="-6v" tar -caf "$(PKG)_$(VER)$(DTYPE).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
	&& $(RM) -r "$(PKG)-$(VER)"
