#  -*- mode: cmake -*-

#
# Build TPL:  CLM
#   
# --- Define all the directories and common external project flags
define_external_project_args(CLM
                             TARGET clm)

# add version to the autogenerated tpl_versions.h file
include(${SuperBuild_SOURCE_DIR}/TPLVersions.cmake)
amanzi_tpl_version_write(FILENAME ${TPL_VERSIONS_INCLUDE_FILE}
                         PREFIX CLM
                         VERSION ${CLM_VERSION_MAJOR} ${CLM_VERSION_MINOR} ${CLM_VERSION_PATCH})

# --- Define the arguments passed to CMake.
# NOTE: hard-coded Debug here is necessary until CLM is safely working...                      
set(CLM_CMAKE_ARGS 
      "-DCMAKE_INSTALL_PREFIX:FILEPATH=${TPL_INSTALL_PREFIX}"
      "-DUNSTRUCTURED_HOST:BOOL=ON"
      "-DBUILD_SHARED_LIBS:BOOL=${BUILD_SHARED_LIBS}"
      "-DCMAKE_BUILD_TYPE:=Debug"
      "-DCMAKE_Fortran_FLAGS:STRING=-fPIC -w -Wno-unused-variable -ffree-line-length-0 -fbounds-check -funderscoring")

# --- Add external project build and tie to the CLM build target
ExternalProject_Add(${CLM_BUILD_TARGET}
                    DEPENDS   ${CLM_PACKAGE_DEPENDS}           # Package dependency target
                    TMP_DIR   ${CLM_tmp_dir}                   # Temporary files directory
                    STAMP_DIR ${CLM_stamp_dir}                 # Timestamp and log directory
                    # -- Download and URL definitions     
                    DOWNLOAD_DIR   ${TPL_DOWNLOAD_DIR}
                    URL            ${CLM_URL}                  # URL may be a web site OR a local file
                    URL_MD5        ${CLM_MD5_SUM}              # md5sum of the archive file
                    DOWNLOAD_NAME  ${CLM_SAVEAS_FILE}          # file name to store (if not end of URL)
                    # -- Configure
                    SOURCE_DIR    ${CLM_source_dir}            # Source directory
                    CMAKE_ARGS    ${AMANZI_CMAKE_CACHE_ARGS}   # Global definitions from root CMakeList
                                  ${CLM_CMAKE_ARGS}
                                  -DCMAKE_C_FLAGS:STRING=${Amanzi_COMMON_CFLAGS}  # Ensure uniform build
                                  -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER}
                                  -DCMAKE_Fortran_COMPILER:FILEPATH=${CMAKE_Fortran_COMPILER}
                    # -- Build
                    BINARY_DIR       ${CLM_build_dir}          # Build directory 
                    BUILD_COMMAND    $(MAKE) VERBOSE=1
                    # -- Install
                    INSTALL_DIR      ${TPL_INSTALL_PREFIX}     # Install directory
                    INSTALL_COMMAND  $(MAKE) install
                    # -- Output control
                    ${CLM_logging_args})

include(BuildLibraryName)
build_library_name(clm CLM_LIB APPEND_PATH ${TPL_INSTALL_PREFIX}/lib)
set(CLM_INCLUDE_DIRS ${TPL_INSTALL_PREFIX}/include)
set(CLM_DIR ${TPL_INSTALL_PREFIX})
