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

MAKEFILE = $(firstword $(MAKEFILE_LIST))
DEBIAN_DIR = $(dir $(MAKEFILE))
DEB_VERSION = $(shell dpkg-parsechangelog -l$(DEBIAN_DIR)/changelog | grep ^Vers | cut -d\  -f2)
DEB_SOURCE_NAME = $(shell dpkg-parsechangelog -l$(DEBIAN_DIR)/changelog | grep ^Source | cut -d" " -f2)
VERSION = $(shell echo $(DEB_VERSION) | sed 's,-.*,,' | sed 's,+dfsg.*,,')
DEB_CLI_ABI_VERSION = 6.4
DEB_CLI_API_VERSION = 6.4.3

override_dh_auto_build:
	# unpack signing key
	cd debian && uudecode < snk.uu
	
	# compile & sign lib
	xbuild Source/MySql.Data/MySql.Data.csproj	

	# build API docs
	mdoc update \
		-i $(CURDIR)/Source/MySql.Data/MySql.Data.xml \
		-o $(CURDIR)/Source/MySql.Data/bin/Debug/monodocer \
		$(CURDIR)/Source/MySql.Data/bin/Debug/MySql.Data.dll
	cd Source/MySql.Data/bin/Debug && mdoc assemble -o MySql.Data monodocer

override_dh_makeclilibs:
	dh_makeclilibs -i -m $(DEB_CLI_API_VERSION)

override_dh_clideps:
	dh_clideps --exclude-moduleref=secur32 --exclude-moduleref=secur32.Dll

override_dh_install:
	# <$(MAKE) install>
	mkdir -p $(CURDIR)/debian/tmp/usr/lib/mysql-connector-net
	cp $(CURDIR)/Source/MySql.Data/bin/Debug/MySql.Data.* $(CURDIR)/debian/tmp/usr/lib/mysql-connector-net/
	# </$(MAKE) install>
	
	# pkg-config
	install -D $(CURDIR)/debian/mysql-connector-net.pc \
	           $(CURDIR)/debian/tmp/usr/lib/pkgconfig/mysql-connector-net.pc
	perl -pe 's/#VERSION#/$(VERSION)/' -i \
	  $(CURDIR)/debian/tmp/usr/lib/pkgconfig/mysql-connector-net.pc
	perl -pe 's/#DEB_CLI_ABI_VERSION#/$(DEB_CLI_ABI_VERSION)/' -i \
	  $(CURDIR)/debian/tmp/usr/lib/pkgconfig/mysql-connector-net.pc
	dh_install

override_dh_auto_clean: 
	xbuild Source/MySql.Data/MySql.Data.csproj /target:clean
	rm -f debian/mysql.snk
	rm -fr Source/MySql.Data/bin
	dh_auto_clean

get-orig-source:
	uscan \
		--package $(DEB_SOURCE_NAME) \
		--watchfile $(DEBIAN_DIR)/watch \
		--upstream-version $(VERSION) \
		--download-version $(VERSION) \
		--destdir . \
		--force-download
	mkdir $(DEB_SOURCE_NAME)-$(VERSION)
	unzip mysql-connector-net-$(VERSION)-src.zip -d $(DEB_SOURCE_NAME)-$(VERSION)
	tar --mtime=@1230768000 -cf ./$(DEB_SOURCE_NAME)_$(VERSION).orig.tar $(DEB_SOURCE_NAME)-$(VERSION)
	gzip -9fn ./$(DEB_SOURCE_NAME)_$(VERSION).orig.tar
	rm -r $(DEB_SOURCE_NAME)-$(VERSION) mysql-connector-net-$(VERSION)-src.zip

%:
	dh $@ --with cli
