install_path <- file.path(getwd(), "inst")

cmake <- biocmake::find()

raw_options <- biocmake::configure(fortran.compiler=FALSE)

raw_options <- c(
    raw_options, 
    BUILD_TESTING="OFF",
    BUILD_SHARED_LIBS="OFF",
    CMAKE_INSTALL_PREFIX=install_path,
    CMAKE_PREFIX_PATH=install_path,
    NULL
)

build_path <- "_build_hdf5"

source_path <- "vendor/hdf5"
h5_raw_options <- c(
    raw_options,
    HDF5_BUILD_CPP_LIB="ON",
    HDF5_BUILD_TOOLS="OFF",
    HDF5_BUILD_EXAMPLES="OFF",
    HDF5_ENABLE_Z_LIB_SUPPORT="ON",
    HDF5_ENABLE_SZIP_SUPPORT="ON",
    HDF5_USE_LIBAEC_STATIC="ON",
    HDF5_ENABLE_ROS3_VFD="ON",
    NULL
)

if (.Platform$OS.type == "windows") {
    h5_raw_options[["CMAKE_C_FLAGS"]] <- paste(h5_raw_options[["CMAKE_C_FLAGS"]], "-DCURL_STATICLIB")
}

h5_options <- biocmake::formatArguments(h5_raw_options)
if (system2(cmake, c("-S", source_path, "-B", build_path, h5_options)) != 0) {
    stop("failed to configure the HDF5 library with CMake")
}

status <- system2(cmake, c("--build", build_path))
if (status != 0) {
    stop("failed to build the HDF5 library with CMake")
}

dir.create("inst", showWarnings=FALSE)
status <- system2(cmake, c("--install", build_path), stderr=FALSE)
if (status != 0) {
    stop("failed to install the HDF5 library with CMake")
}
