#!/usr/bin/env python3
import os
import subprocess
from sys import platform

ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
OUT_PATH = os.path.join(ROOT_DIR, ".bazelrc")


def run_cmd(cmd):
    try:
        output = subprocess.check_output(
            cmd.split(" "), stderr=subprocess.STDOUT
        ).decode()
    except subprocess.CalledProcessError as e:
        output = e.output.decode()
        raise RuntimeError(output)
    return output.rstrip()


def main():
    with open(OUT_PATH, "w") as f:
        # TODO: add ubsan + msan builds also
        f.write(
            """
build --cxxopt="-std=c++14"
build --cxxopt="-Wall"
build --cxxopt="-fopenmp"
build --linkopt -fopenmp

# ASAN build
# TODO: add ubsan + msan builds also
build:asan --strip=never
build:asan --copt -fsanitize=address
build:asan --copt -DADDRESS_SANITIZER
build:asan --copt -O1
build:asan --copt -g
build:asan --copt -fno-omit-frame-pointer
build:asan --linkopt -fsanitize=address
"""
        )

        # Get R related paths
        r_include_path = run_cmd("Rscript -e cat(Sys.getenv('R_INCLUDE_DIR'))")
        r_lib_path = run_cmd("Rscript -e cat(Sys.getenv('R_HOME'))") 
        r_lib_path = os.path.join(r_lib_path, 'lib')
        f.write(
f"""
build --action_env=R_INCLUDE_DIR={r_include_path}
build --linkopt="-L{r_lib_path}"
"""
        )

        conda_prefix = os.environ["CONDA_PREFIX"]
        conda_bin = os.path.join(conda_prefix, "bin")
        conda_inc = os.path.join(conda_prefix, "include")
        conda_lib = os.path.join(conda_prefix, "lib")

        # MacOS
        if platform == "darwin":
            # get canonical omp path
            sdk_path = run_cmd("xcrun --sdk macosx --show-sdk-path")
            f.write(
                f"""
# Use clang from conda-forge
build --action_env=CC={conda_bin}/clang
build --action_env=CXX={conda_bin}/clang++
build --action_env=BAZEL_CXXOPTS=-isystem{conda_inc}
build --action_env=BAZEL_LINKOPTS=-L{conda_lib}:-Wl,-rpath,{conda_lib}
build --action_env=SDKROOT={sdk_path}
# Tell Bazel not to use the full Xcode toolchain on Mac OS
build --repo_env=BAZEL_USE_CPP_ONLY_TOOLCHAIN=1"""
            )
        else:
            # Linux
            f.write(
                f"""
build --linkopt=-L{conda_lib}

# Linux GCC
build:gcc --action_env=CC=gcc
build:gcc --action_env=CXX=g++

# Linux Clang (default)
build --action_env=CC=clang
build --action_env=CXX=clang++
"""
            )


if __name__ == "__main__":
    main()
