#!/usr/bin/make -f
# -*- makefile -*-

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

PKGNAME=$(shell grep Package: debian/control.in|cut -d' ' -f2)
GRASS=grass$(subst .,,$(shell pkg-config --modversion grass|cut -d. -f1,2))
GRASS_ABI=grass$(subst .,,$(shell pkg-config --modversion grass|cut -d. -f1,2,3|sed -e 's/RC/-/'))
GDAL=$(shell cat VERSION|cut -d. -f1,2)

# Abort if source and gdal have not the same versions.
ifneq ($(shell gdal-config --version),$(shell cat VERSION))
$(error GDAL version and GDAL GRASS plugin version are not aligned. Please, upload a proper plugin source version.)
endif

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

override_dh_autoreconf:
	mv configure configure.pre-autoreconf
	dh_autoreconf

override_dh_autoreconf_clean:
	dh_autoreconf_clean
	if [ -e "configure.pre-autoreconf" ]; then \
		mv configure.pre-autoreconf configure ; \
	fi

override_dh_auto_configure:
	sed -e 's/@GRASS_ABI@/$(GRASS_ABI)/' debian/control.in > debian/control

	sed -e 's/@GDAL@/$(GDAL)/' -e 's/@GRASS@/$(GRASS)/' -e 's/@PKGNAME@/$(PKGNAME)/' debian/lintian-overrides.in > debian/$(PKGNAME).lintian-overrides

	@echo "Depending on $(GRASS)"
	if [ `grep "$(GRASS_ABI)" debian/control|wc -l` -eq 0 ]; then \
		sed -e 's/@GRASS_ABI@/$(GRASS_ABI)/' debian/control.in > debian/control; \
	fi

	dh_auto_configure -- --prefix=/usr --with-grass=/usr/lib/$(GRASS) --with-autoload=/usr/lib/gdalplugins/$(GDAL)

override_dh_auto_install:
	mkdir -p $(CURDIR)/debian/$(PKGNAME)/usr/lib/$(GDAL)/grass

	$(MAKE) install AUTOLOAD_DIR=$(CURDIR)/debian/$(PKGNAME)/usr/lib/gdalplugins/$(GDAL) \
			GRASSTABLES_DIR=$(CURDIR)/debian/$(PKGNAME)/usr/lib/$(GDAL)/grass

	# removes redundant stuff already installed by grass
	rm -rf $(CURDIR)/debian/$(PKGNAME)/usr/lib/$(GDAL)

override_dh_shlibdeps:
	dh_shlibdeps -l.:/usr/lib/$(GRASS)/lib 

