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

%:
	dh $@

override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	set -e \
	;for F in $$(find plugins -type f -name '*.sqlite'); do \
	    echo "checking $$F" ;\
	    R="$$(sqlite3 $$F 'pragma integrity_check;')" ;\
	    if [ "$$R" != "ok" ]; then \
	        echo -e "E: $$R\n" && false; \
	    fi \
	;done
endif

override_dh_gencontrol:
	dh_gencontrol -- -Vuver=$(VER)

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

$(PKG)_$(VER)$(DTYPE).orig.tar.xz:
	@echo "# Downloading..."
	wget --tries=3 --timeout=40 --read-timeout=40 --continue -O $(PKG)_$(VER).orig.tar.gz \
          http://www.mirrorservice.org/sites/ftp.mysql.com/Downloads/MySQLGUITools/mysql-workbench-community-$(VER)-src.tar.gz
	#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..."
	cd $(PKG)-$(VER) \
        && find . -type f -printf "\"%p\"\n" | grep -v -E '\./plugins/wb.doclib|\./ChangeLog|\./COPYING' | xargs $(RM) \
        && find . -type d -empty -delete \
	#$(RM) -v $(PKG)_$(VER).orig.tar.*
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | sort \
        | XZ_OPT="-7v" tar -caf "$(PKG)_$(VER)$(DTYPE).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
        && $(RM) -r "$(PKG)-$(VER)"
