#!/usr/bin/make -f

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

LIB := $$(python -c "from distutils.command.build import build ; from distutils.core import Distribution ; b = build(Distribution()) ; b.finalize_options() ; print b.build_platlib")

%:
	dh $@ --with python2

override_dh_clean:
	dh_clean
	$(RM) -r build
	$(RM) -rf mysql/connector/
	find scripts -mindepth 1 -regex '[^.]*' -delete -printf 'removing %p\n'

TESTS=$(wildcard unit_tests/test*.py)
override_dh_auto_test:
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	# Link mysql.connector directory in the build dir, as they share the same ns
	# we cd to / as otherwise we pick the local mysql/ dir
	ln -s $$(dirname $$(cd / ; python -c "import mysql.connector as p; print p.__file__" ; cd $(CURDIR))) $(CURDIR)/$(LIB)/mysql
	set -e \
	;for python in $(shell pyversions -r); do \
	    for test in $(TESTS); do \
	        echo -e "\n### $$python::$$test" ;\
	        PYTHONPATH="$(CURDIR)/$(LIB)" $$python $$test ;\
	    done \
	;done
	rm $(CURDIR)/$(LIB)/mysql/connector
endif

override_dh_builddeb:
	dh_builddeb -- -Zxz

override_dh_installdocs:
	dh_installdocs README*

override_dh_python2:
	dh_python2 --no-guessing-deps

MAN_NAME=show CREATE TABLE from .frm files
mysqlfrm.1:
	PYTHONPATH=. help2man --no-discard-stderr --no-info --name="$(MAN_NAME)" --version-string=" " ./scripts/mysqlfrm > $@
	perl \
             -E 's{\s+(It was generated by help2man)}{ $$1};   # correcting help2man comment'               \
             -E 's{\s+\K\-\-}{\\-\\-}g;                        # correcting hyphen-used-as-minus-sign'      \
          -pi $@
	MANROFFSEQ='' MANWIDTH=80 man --warnings -E UTF-8 -l -Tutf8 -Z $@ >/dev/null

PKD  = $(abspath $(dir $(MAKEFILE_LIST)))
PKG  = $(word 2,$(shell dpkg-parsechangelog -l$(PKD)/changelog | grep ^Source))
VER ?= $(shell dpkg-parsechangelog -l$(PKD)/changelog | perl -ne 'print $$1 if m{Version:\s*([\d\.+git]+)}')
## get-orig-source
get-orig-source: $(info I: $(PKG)_$(VER))
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))
	@echo "# Downloading..."
	uscan --noconf --verbose --rename --destdir=$(CURDIR) --check-dirname-level=0 --force-download --download-version $(VER) $(PKD)
	#bzr checkout --hardlink --lightweight --revision=tag:release-$(VER) \
	#  https://code.launchpad.net/~mysql/mysql-utilities/trunk $(PKG)-$(VER) \
	#|| $(RM) -r $(PKG)-$(VER)
	#@echo "Cleaning and Packing..."
	#$(RM) -r $(PKG)-$(VER)/.bzr*
	#tar -caf "$(PKG)_$(VER).orig.tar.xz" "$(PKG)-$(VER)" \
	#&& $(RM) -r "$(PKG)-$(VER)"
