#!/usr/bin/make -f

# Extract external sources from the -orig-external tarball
export ISLANDHACK_CACHE=$(shell pwd)/external
export ISLANDHACK_LOG=$(shell pwd)/islandhack.log

# Bazel not only thinks it's appropriate to dump garbage in
# $HOME/.cache/, but will throw a fit if $HOME is a subdirectory of
# the current directory.
export HOME=/tmp/bazel.sucks.$(shell pwd | tr / _)

ifeq ($(shell dpkg-architecture -qDEB_HOST_GNU_CPU),x86_64)
cc_opt_flags = -mtune=generic -msse3
else
cc_opt_flags = -mtune=generic
endif

ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
jobs = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS)))
else
jobs = 1
endif

%:
	dh $@ --with python2,python3

override_dh_auto_configure:

override_dh_auto_build:
	mkdir -p $(HOME)
	set -e; for ver in 2 3; do \
	  PYTHON_BIN_PATH=/usr/bin/python$$ver \
	  CC_OPT_FLAGS="$(cc_opt_flags)" \
	  TF_NEED_JEMALLOC=1 \
	  TF_NEED_GCP=0 \
	  TF_NEED_HDFS=0 \
	  TF_ENABLE_XLA=0 \
	  USE_DEFAULT_PYTHON_LIB_PATH=1 \
	  TF_NEED_OPENCL=0 \
	  TF_NEED_CUDA=0 \
	  islandhack ./configure </dev/null; \
	  islandhack bazel build --jobs $(jobs) -c opt \
	      //tensorflow/tools/pip_package:build_pip_package ; \
	  ./bazel-bin/tensorflow/tools/pip_package/build_pip_package \
	      `pwd`/pip-package-$$ver ; \
	done

override_dh_auto_install:
	set -e; for ver in 2 3; do \
	  pkg=`echo python$$ver-tensorflow | sed s/python2/python/`; \
	  whl=`basename pip-package-$$ver/*.whl` ; \
	  pip$$ver install --system --no-deps --root debian/$$pkg \
	    --prefix /usr pip-package-$$ver/$$whl ; \
	done
	find debian -type f -path '*/include/*' -exec chmod a-x {} +

override_dh_usrlocal:

override_dh_python2:
	dh_python2 -v --no-ext-rename
	dh_numpy -ppython-tensorflow

override_dh_python3:
	dh_python3 -v --no-ext-rename
	dh_numpy3 -ppython3-tensorflow

override_dh_auto_test:
# ????

override_dh_auto_clean:
	-bazel clean --expunge
	rm -rf /tmp/bazel.sucks.$(shell pwd | tr / _)
	rm -rf pip-package-2
	rm -rf pip-package-3
	rm -f islandhack.log
