#!/bin/bash

set -ex

# A modified version of the protobuf BUILD file is required to add -lm to the
# link options. See: https://github.com/tensorflow/tensorflow/issues/1171
cp ${RECIPE_DIR}/custom_protobuf.BUILD custom_protobuf.BUILD

# This modification is pulled in by changing protobuf to a new_http_archive
# and specifying the build_file in a modification to the workspace.bzl file.
# This file also adds file:// urls to many of the external dependencies so that
# they can be cached locally in the /tf_cache directory to speed up builds.
# Use the download_dependencies.sh script to download these files.
rm tensorflow/workspace.bzl
cp ${RECIPE_DIR}/workspace.bzl tensorflow/workspace.bzl

# configure the build
export PYTHON_BIN_PATH=${PYTHON}
export PYTHON_LIB_PATH=${SP_DIR}
export CC_OPT_FLAGS="-march=nocona"
# disable jemmloc (needs MADV_HUGEPAGE macro which is not in glib <= 2.12)
export TF_NEED_JEMALLOC=0
export TF_NEED_GCP=0
export TF_NEED_HDFS=0
export TF_ENABLE_XLA=0
export TF_NEED_OPENCL=0
# CUDA details, these should be customized depending on the system details
export TF_NEED_CUDA=1
export TF_CUDA_VERSION="7.5"
export TF_CUDNN_VERSION="5"
# Additional compute capabilities can be added if desired but these increase
# the build time and size of the package. The ones here are the ones supported
# by CUDA 7.5 and used in the devel-gpu tensorflow docker image:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/docker/Dockerfile.devel-gpu
# 6.0 and 6.1 should be added with CUDA version 8.0
export TF_CUDA_COMPUTE_CAPABILITIES="3.0,3.5,5.2"
export GCC_HOST_COMPILER_PATH="/opt/rh/devtoolset-2/root/usr/bin/gcc"
export CUDA_TOOLKIT_PATH="/usr/local/cuda"
export CUDNN_INSTALL_PATH="/usr/local/cuda"
./configure

# rt library needed for glibc <2.17
export LDFLAGS="-lrt"
export CFLAGS="-I${PREFIX}/include -L${PREFIX}/lib $CFLAGS"
export CXXFLAGS="-I${PREFIX}/include -L${PREFIX}/lib $CXXFLAGS"

# build using bazel
# for debugging the following lines may be helpful
#    --logging=6 \
#    --subcommands \
#    --verbose_failures \
bazel build \
    --config=opt \
    --config=cuda \
    --color=yes \
    --curses=no \
    //tensorflow/tools/pip_package:build_pip_package

# build a whl file
mkdir $SRC_DIR/tensorflow_pkg
bazel-bin/tensorflow/tools/pip_package/build_pip_package $SRC_DIR/tensorflow_pkg

# install using pip from the whl file
pip install --no-deps $SRC_DIR/tensorflow_pkg/*.whl
