#!/usr/bin/make -f

# Use existing lib_lightgbm.so when calling setup.py
export PYBUILD_INSTALL_ARGS=--precompile

# Get version from changelog as well as lsb_release
# to compute unique build version (useful for repo mirroring systems doing file pooling)
PKG_VERSION  := $(shell dpkg-parsechangelog | egrep '^Version:' | cut -f 2 -d ' ')
DIST_NAME    := $(shell lsb_release -si)
DIST_RELEASE := $(shell lsb_release -sc)
DIST_VERSION := $(shell lsb_release -sr)
PKG_VERSION_TAG := $(PKG_VERSION)+$(DIST_NAME).$(DIST_RELEASE).$(DIST_VERSION)
SUBSTVARS_BINARY_VERSION := -Vbinary:Version="$(PKG_VERSION_TAG)"
SUBSTVARS_SOURCE_VERSION := -Vsource:Version="$(PKG_VERSION_TAG)"


# dh-r is broken :(
# https://github.com/chronitis/dh-r/issues/1
# Information extracted from /usr/share/perl5/Debian/Debhelper/Buildsystem/R.pm
RBASE_VERSION := $(shell dpkg-query -W -f='$${Version}' r-base-dev)
RAPI_VERSION  := $(shell dpkg-query -W -f='$${Provides}' r-base-core | grep -o 'r-api[^, ]*')
R_BUILD_DEPS  := $(shell grep -A 1 @@@@R_DEPS_TOKEN@@@@ debian/control | tail -n 1)
SUBSTVARS_R_DEPENDS := -VR:Depends="r-base-core (>= $(RBASE_VERSION)), $(RAPI_VERSION), $(R_BUILD_DEPS)"

%:
	dh $@ --with python2,python3 --parallel

# https://github.com/Microsoft/LightGBM/wiki/Installation-Guide
override_dh_auto_configure:
	dh_auto_configure -- \
	  -DUSE_MPI=1 \
	  -DUSE_GPU=1 

override_dh_auto_build:
	dh_auto_build
	dh_auto_build --sourcedirectory python-package --buildsystem=pybuild

override_dh_auto_install:
	dh_auto_install
	dh_auto_install --sourcedirectory python-package --buildsystem=pybuild
	mkdir -p debian/tmp/usr/lib/R/site-library
	R CMD INSTALL -l debian/tmp/usr/lib/R/site-library --clean R-package/

override_dh_install:
	# Replaced by dependency on liblightgbm package and symlink
	rm -f debian/tmp/usr/lib/python2.*/dist-packages/lightgbm/lib_lightgbm.so
	rm -f debian/tmp/usr/lib/python3.*/dist-packages/lightgbm/lib_lightgbm.so
	rm -f debian/tmp/usr/lib/R/site-library/lightgbm/LICENSE
	dh_install --fail-missing

override_dh_auto_clean:
	dh_auto_clean
	dh_auto_clean --sourcedirectory python-package --buildsystem=pybuild
	rm -f python-package/lightgbm/VERSION.txt
	rm -rf python-package/lightgbm.egg-info
	rm -f lib_lightgbm.so lightgbm
	rm -rf R-package/src/build R-package/src/src R-package/src/include R-package/src/CMakeLists.txt

override_dh_gencontrol:
	dh_gencontrol -- -v"$(PKG_VERSION_TAG)" $(SUBSTVARS_R_DEPENDS) $(SUBSTVARS_BINARY_VERSION) $(SUBSTVARS_SOURCE_VERSION)
