#!/bin/bash

# Uses [buildozer](https://github.com/bazelbuild/buildtools/tree/master/buildozer) to patch certain rules.

set -euo pipefail
COPTS=(
  "-w"  # Suppress all warnings
  "--std=c++14"
)

RULES=(
    "cc_library"
    "cc_binary"
    "tf_cuda_library"
    "tf_py_wrap_cc"
    "tf_kernel_library"
    "cc_library_with_android_deps"
    "cuda_rdc_library"
    "tf_native_cc_binary"
    "tf_python_pybind_extension"
    "pybind_extension"
)

run_buildozer() {
    set +e
    buildozer -k "$@"
    rc=$?
    set -e
    if [[ ${rc} -ne 0 && ${rc} -ne 3 ]]; then
        # Exit code 3 means no changes were made
        return ${rc}
    fi
    return 0
}

for rule in ${RULES[@]}; do
    for opt in ${COPTS[@]}; do
        run_buildozer -k "add copts ${opt}" //...:%${rule}
    done
done

run_buildozer "remove exec_properties" //...:%py_test

run_buildozer "add copts -fpermissive" //tensorflow/compiler/xla/service/gpu:ir_emitter

# Patching build files that aren't named BUILD or BUILD.bazel. buildozer can only work on
# build files thus named.
fix_build_file() {
    FILENAME=$1

    TEMP_DIR=$(mktemp -d --tmpdir tmp-fixbuild-$(basename ${FILENAME} .BUILD)-XXXXXXXX)
    cp ${FILENAME} ${TEMP_DIR}/BUILD
    touch ${TEMP_DIR}/WORKSPACE

    (
        cd ${TEMP_DIR}
        for opt in ${COPTS[@]}; do
            for rule in ${RULES[@]}; do
                run_buildozer -k "add copts ${opt}" //...:%${rule}
            done
        done
    )

    mv -f ${TEMP_DIR}/BUILD $FILENAME
    rm -r ${TEMP_DIR}
}

THIRD_PARTY_BUILDS=(
    "gif.BUILD"
    "llvm/llvm.autogenerated.BUILD"
    "jsoncpp.BUILD"
    "mkl_dnn/mkldnn.BUILD"
    "pcre.BUILD"
    "sqlite.BUILD"
    "swig.BUILD"
    "nccl/archive.BUILD"
)

for f in ${THIRD_PARTY_BUILDS[@]}; do
    fix_build_file third_party/${f}
done

buildozer "rename additional_deps deps" //tensorflow/contrib/...:%tf_py_test
buildozer "rename additional_deps deps" //tensorflow/contrib/...:%cuda_py_test
