#!/usr/bin/make -f
include /usr/share/dpkg/pkg-info.mk

#we need to know the R version
RVERS = $(shell dpkg-query -W --showformat='$${Version}' r-base-core)
RMAJOR = $(shell echo $(RVERS) | awk -F. '{print $$1}')
RMINOR = $(shell echo $(RVERS) | awk -F. '{print $$2}')

# Workaround for cmake not handling CPPFLAGS (https://wiki.debian.org/HardeningWalkthrough):
# As we cannot easily use dh for configuring, we have to merge flags, manually.
CFLAGS += $(CPPFLAGS)
CXXFLAGS += $(CPPFLAGS)

# easier typing
DESTDIR = $(CURDIR)/debian/tmp
BUILDDIR = $(CURDIR)/debian/build

%:
	dh $@ --buildsystem=cmake --builddirectory=$(BUILDDIR)

override_dh_auto_configure:
	mkdir -p $(BUILDDIR)
	# Some installations of R need a specific version of the compiler(s)
	# R CMD config provides info on which compiler to use
	CC="`/usr/bin/R CMD config CC`" \
	CXX="`/usr/bin/R CMD config CXX`" \
	F77="`/usr/bin/R CMD config F77`" \
	dh_auto_configure '--buildsystem=kf5' --parallel -- \
		-DR_EXECUTABLE=/usr/bin/R/ \
		-DR_LIBDIR=/usr/lib/R/site-library/ \
		-DCMAKE_SKIP_RPATH=YES \
		-DBUILD_TIMESTAMP="$(shell date --utc --date='@$(SOURCE_DATE_EPOCH)')"

override_dh_auto_install:
	dh_auto_install

	# dirty hack to get rid of conflicting r.xml file without adjusting all makefiles
	rm -vf $(DESTDIR)/usr/share/katepart/syntax/r.xml
	# remove unneeded R package files
	rm -vf $(DESTDIR)/usr/lib/R/site-library/R.css $(DESTDIR)/usr/lib/R/site-library/rkward/COPYING
	# remove x-test locale
	rm -rvf $(DESTDIR)/usr/share/rkward/po/x-test $(DESTDIR)/usr/share/locale/x-test

override_dh_compress:
	# do not compress KDE HTML help
	dh_compress -Xusr/share/doc/kde/HTML

override_dh_shlibdeps:
	dh_shlibdeps
	# unfortunately, the r-base-core dependency can not be found by dh_shlibdeps, so we need to get at the version manually
	# NOTE: This "if" is currently always true (see build-deps), but left here, for convenience, in case we get into trouble
	# with binary incompatibility (esp. foward incompatibility) again, in the future.
	@if [ "$(RMAJOR)" -eq "3" ] && [ "$(RMINOR)" -ge "0" ] ; then \
		echo "rvers=r-base-core (>= $(RVERS))" >> $(CURDIR)/debian/rkward.substvars ; \
		echo "rapivers=r-api-3.4" >> $(CURDIR)/debian/rkward.substvars ; \
	fi
