#!/usr/bin/make -f
# -*- makefile -*-
# debian/rules for Ginkgo CADx

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

# minimise needless linking
export DEB_LDFLAGS_MAINT_APPEND= -Wl,--as-needed

## Disable wx3.0 WXDEBUG checks, as happened by default in wx2.8.
## (This is necessary to avoid segfaults with wx3.0).
export DEB_CPPFLAGS_MAINT_APPEND=-DNDEBUG

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\.]+)}')

DH=--buildsystem=cmake --sourcedirectory=src --parallel
%:
	dh $@ $(DH)

override_dh_auto_configure:
	dh_auto_configure $(DH) -- \
            -DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo \
            -DCMAKE_CXX_FLAGS_RELEASE="$(CXXFLAGS) $(CPPFLAGS)" \
            -DCMAKE_CXX_FLAGS_RELWITHDEBINFO="$(CXXFLAGS) $(CPPFLAGS)"

override_dh_auto_install:
	dh_auto_install $(DH) --destdir=$(CURDIR)/debian/tmp
	
	## Hack around useless rpath definitions
	#/usr/bin/chrpath -r /usr/lib/ginkgocadx debian/$(PKG)/usr/bin/$(PKG)

override_dh_installchangelogs:
	dh_installchangelogs changelog_opensource.txt

## avoid post{inst|rm}-useless-call-to-ldconfig
override_dh_makeshlibs:
	dh_makeshlibs --noscripts

override_dh_strip:
	[ -d "$(CURDIR)/debian/$(PKG)-dbg" ] \
        && dh_strip --dbg-package=$(PKG)-dbg \
        || dh_strip

override_dh_builddeb:
	dh_builddeb -- -Zxz

## http://wiki.debian.org/onlyjob/get-orig-source
DTYPE := +dfsg
.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..."
	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 2 \
        || $(RM) -r $(PKG)-$(VER)
	@echo "# Clean-up..."
	cd $(PKG)-$(VER) \
        && $(RM) -r -v src/cadxcore/jsoncpp
	@echo "# Correcting permissions..."
	find $(PKG)-$(VER) -type f -executable -exec chmod --changes a-x '{}' \;
	@echo "# Packing..."
	find -L "$(PKG)-$(VER)" -xdev -type f -print | sort \
        | XZ_OPT="-6v" tar -caf "$(PKG)_$(VER)$(DTYPE).orig.tar.xz" -T- --owner=root --group=root --mode=a+rX \
        && $(RM) -r "$(PKG)-$(VER)"
