#!/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))

API=-$(shell perl -ne 'print $$1 if m{LIBBLKMAKER_API_VERSION\],\s*\[([\d\.]+)\]}' configure.ac)-
plib=$(PKG)$(API)0
pdev=$(PKG)$(API)dev
pdbg=$(PKG)$(API)dbg

# Ensure the build aborts when there are still references to undefined
# symbols: LDFLAGS += -Wl,-z,defs

# Make the linker work a bit harder so dynamic loading can be done
# faster: LDFLAGS += -Wl,-O1

export DEB_LDFLAGS_MAINT_APPEND=-Wl,-z,defs -Wl,-O1

%:
	dh $@ --parallel --with autoreconf

override_dh_auto_install:
	dh_auto_install --destdir=$(CURDIR)/debian/tmp

override_dh_install:
	$(info I: library-name=$(plib))
	$(if $(wildcard debian/$(plib).symbols),,$(error invalid package/library name..))
	dh_install -p$(plib) --autodest    \
            usr/lib/*/lib*-[0-9]*.so.*
	dh_install -p$(pdev) --autodest      \
            usr/include/*/*                   \
            usr/lib/*/lib*-[0-9.]*.so          \
            usr/lib/*/pkgconfig/lib*-[0-9.]*.pc

override_dh_installdocs:
	dh_installdocs --link-doc=$(plib)

# not needed when .symbols present
#override_dh_makeshlibs:
#	dh_makeshlibs -v -V

override_dh_gencontrol:
	dh_gencontrol -v -- -Vplib=$(plib)

# gracefully handle stripping if -dbg package (un-)commented in debian/control
override_dh_strip:
	[ -d "$(CURDIR)/debian/$(pdbg)" ] \
        && dh_strip --dbg-package=$(pdbg) \
        || dh_strip

override_dh_builddeb:
	dh_builddeb -- -Zxz

## http://wiki.debian.org/onlyjob/get-orig-source
VER ?= $(shell dpkg-parsechangelog -l$(PKD)/changelog | perl -ne 'print $$1 if m{^Version:\s+(?:\d+:)?(\d.*)(?:\-\d+.*)};')
.PHONY: get-orig-source
get-orig-source: $(PKG)_$(VER).orig.tar.xz
	@

UURL = git://gitorious.org/bitcoin/libblkmaker.git
$(PKG)_$(VER).orig.tar.xz:
	$(if $(wildcard $(PKG)-$(VER)),$(error $(PKG)-$(VER) exist, aborting..))
	@echo "# Downloading..."
	git clone $(UURL) $(PKG)-$(VER) \
        || $(RM) -r $(PKG)-$(VER)
	cd $(PKG)-$(VER) \
        && git checkout v$(VER) \
        && echo "# Setting times..." \
        && for F in $$(git ls-tree -r --name-only HEAD); do touch --no-dereference -d "$$(git log -1 --format="%ai" -- $$F)" "$$F"; done \
        && [ -s ChangeLog ] || ( echo "# Generating ChangeLog..." \
           ; git log --pretty="format:%ad  %aN  <%aE>%n%n%x09* %s%n" --date=short > ChangeLog \
           ; touch -d "$$(git log -1 --format='%ci')" ChangeLog) \
        && $(RM) -r .git .git*
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | sort \
        | XZ_OPT="-6v" tar -caf "$(PKG)_$(VER).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
        && $(RM) -r "$(PKG)-$(VER)"
