#!/usr/bin/make -f

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+.*)};')
REV   = $(shell echo $(VER) | perl -ne 'print "$$1" if m/(?:git|svn|hg|bzr)(\d+)/;')
UURL = lp:loggerhead
DTYPE = +dfsg
VER  ?= $(subst $(DTYPE),,$(UVER))

%:
	dh $* --with python3 --buildsystem=pybuild

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
CONCURRENCY = BZR_CONCURRENCY=$(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
endif

ifeq (,$(findstring nocheck,$(DEB_BUILD_OPTIONS)))
override_dh_auto_test:
	PYTHONPATH=$(CURDIR) $(CONCURRENCY) BRZ_PLUGINS_AT=loggerhead@$(CURDIR) /usr/bin/brz selftest \
	    --parallel=fork -v -s bp.loggerhead
endif

override_dh_auto_clean:
	dh_auto_clean
	cd docs/ && $(MAKE) clean

override_dh_auto_build:
	dh_auto_build
	cd docs/ && $(MAKE) html

$(PKG)_$(VER)$(DTYPE).orig.tar.xz:
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))
	bzr export --revision=$(REV) $(PKG)-$(VER) $(UURL) \
	|| $(RM) -r $(PKG)-$(VER)
	@echo "# Removing copy of YUI3..."
	cd $(PKG)-$(VER) \
		&& $(RM) -r -v \
		loggerhead/static/javascript/yui
	@echo "# Packing..."
	XZ_OPT="-6v" tar -caf "$(PKG)_$(VER)$(DTYPE).orig.tar.xz" "$(PKG)-$(VER)" \
	&& $(RM) -r "$(PKG)-$(VER)"
