#!/usr/bin/make -f
export DEB_BUILD_MAINT_OPTIONS = hardending=+all
export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed

LUA51=/usr/bin/lua5.1
LUAJIT=/usr/bin/luajit

export CC=gcc-6
export CXX=g++-6

TORCH_FLAGS_5_1= \
 -DLUA=/usr/bin/lua5.1 \
 -DLUA_INCDIR=/usr/include/lua5.1 \
 -DLUA_LIBDIR=/usr/lib \
 -DLUA_BINDIR=/usr/bin \
 -DLIBDIR=/usr/lib \
 -DLUALIB=lua5.1 \
 -DTorch_INSTALL_BIN_SUBDIR=bin/ \
 -DTorch_INSTALL_LIB_SUBDIR=lib/$(DEB_HOST_MULTIARCH)/ \
 -DTorch_INSTALL_INCLUDE_SUBDIR=include/ \
 -DCMAKE_VERBOSE_MAKEFILE=ON \
 -DCMAKE_BUILD_TYPE=Release \
 -DCMAKE_INSTALL_PREFIX=/usr \
 -DCMAKE_C_FLAGS="-I/usr/include/TH -g" \
 -DCMAKE_CXX_FLAGS="-I/usr/include/TH -g" \
 -DTorch_FOUND=ON

%:
	dh $@ --buildsystem=lua --with lua

override_dh_auto_configure:
	ln -s . cutorch
	# configure libTHC.so
	dh_auto_configure --buildsystem=cmake --builddirectory=THC.build -- \
		../lib/THC ${TORCH_FLAGS_5_1} \
		-DTorch_INSTALL_CMAKE_SUBDIR=/usr/share/libtorch-thc-dev/
	# configure the rest lua stuff
	dh_auto_configure --buildsystem=lua
	# generate TensorMath.c (equivalent to `ADD_TORCH_WRAP(cudatensormathwrap TensorMath.lua)`)
	$(LUA51) TensorMath.lua TensorMath.c
	# configure install templates
	sed -e 's/#DEB_HOST_MULTIARCH#/$(DEB_HOST_MULTIARCH)/g' \
		< debian/libtorch-thc-dev.install.in > debian/libtorch-thc-dev.install
	sed -e 's/#DEB_HOST_MULTIARCH#/$(DEB_HOST_MULTIARCH)/g' \
		< debian/libtorch-thc.install.in > debian/libtorch-thc.install

override_dh_auto_build:
	# build libTHC.so
	dh_auto_build --buildsystem=cmake -B THC.build/ --parallel
	# build the rest lua stuff
	dh_auto_build --buildsystem=lua

override_dh_auto_install:
	# install libTHC.so
	dh_auto_install --buildsystem=cmake -B THC.build
	# install the rest lua stuff
	dh_auto_install --buildsystem=lua

override_dh_auto_clean:
	-$(RM) -rf THC.build cutorch
	-$(RM) TensorMath.c
	dh_auto_clean
