# -*- python -*-

load(
    "@drake//tools/install:install.bzl",
    "install",
    "install_files",
)

licenses(["by_exception_only"])  # Gurobi

# This rule is only built if a glob() call fails.
genrule(
    name = "error-message",
    outs = ["error-message.h"],
    cmd = "echo 'error: Gurobi 9.0.2 is not installed at {gurobi_home}, export GUROBI_HOME to the correct value' && false",  # noqa
    visibility = ["//visibility:private"],
)

GUROBI_C_HDRS = glob([
    "gurobi-distro/include/gurobi_c.h",
]) or [":error-message.h"]

GUROBI_CXX_HDRS = glob([
    "gurobi-distro/include/gurobi_c.h",
    "gurobi-distro/include/gurobi_c++.h",
]) or [":error-message.h"]

# In the Gurobi package, libgurobi90.so is a symlink to libgurobi.so.9.0.0.
# However, if we use libgurobi.so.9.0.0 in srcs, executables that link this
# library will be unable to find it at runtime in the Bazel sandbox,
# because the NEEDED statements in the executable will not square with the
# RPATH statements.  I don't really know why this happens, but I suspect it
# might be a Bazel bug.

GUROBI_C_SRCS = glob([
    "gurobi-distro/lib/libgurobi90.so",
]) or [":error-message.h"]

GUROBI_CXX_SRCS = glob([
    "gurobi-distro/lib/libgurobi90.so",
    "gurobi-distro/lib/libgurobi_g++5.2.a",
]) or [":error-message.h"]

GUROBI_INSTALL_LIBRARIES = glob([
    "gurobi-distro/lib/libgurobi.so.9.0.2",
    "gurobi-distro/lib/libgurobi90.so",
]) or [":error-message.h"]

GUROBI_DOCS = glob([
    "gurobi-distro/EULA.pdf",
]) or [":error-message.h"]

cc_library(
    name = "gurobi_c",
    srcs = GUROBI_C_SRCS,
    hdrs = GUROBI_C_HDRS,
    includes = ["gurobi-distro/include"],
    linkopts = ["-pthread"],
    visibility = ["//visibility:public"],
)

cc_library(
    name = "gurobi_cxx",
    srcs = GUROBI_CXX_SRCS,
    hdrs = GUROBI_CXX_HDRS,
    includes = ["gurobi-distro/include"],
    linkopts = ["-pthread"],
    visibility = ["//visibility:public"],
)

install_files(
    name = "install_libraries",
    dest = ".",
    files = GUROBI_INSTALL_LIBRARIES,
    strip_prefix = ["gurobi-distro"],
    visibility = ["//visibility:private"],
)

install(
    name = "install",
    docs = GUROBI_DOCS,
    doc_strip_prefix = ["gurobi-distro"],
    visibility = ["//visibility:public"],
    deps = [":install_libraries"],
)
