# Build DL_FIELD as a shared library using its native Makefile

#  Copyright (C) 2017 The authors of Py-ChemShell
#
#  This file is part of Py-ChemShell.
#
#  Py-ChemShell is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as
#  published by the Free Software Foundation, either version 3 of the
#  License, or (at your option) any later version.
#
#  Py-ChemShell is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public
#  License along with Py-ChemShell.  If not, see
#  <http://www.gnu.org/licenses/>.

# you.lu@stfc.ac.uk
# created 2018
# edited Apr 2019

# if OLDALLOC for pgf95, uncomment:
option(OLDALLOC "Old alloction for pgf95" OFF)
if(OLDALLOC)
  add_definitions(-DOLDALLOC)
endif()

# switch: update source code from svn
# FIXME: not in use
if($ENV{DL_FIELD_UPDATE})
  set(DL_FIELD_NO_UPDATE 0)
else()
  set(DL_FIELD_NO_UPDATE 1)
endif()

# paths
set(CMAKE_Fortran_MODULE_DIRECTORY ${CHEMSH_BUILD_DIR}/modules/dl_field)
set(DL_FIELD_INCLUDE_DIRECTORY     ${CHEMSH_BUILD_DIR}/include/dl_field)
include_directories(${CHEMSH_BUILD_DIR}/modules
                    ${CHEMSH_BUILD_DIR}/modules/parallel
                    ${CHEMSH_BUILD_DIR}/modules/dl_py2f)
file(MAKE_DIRECTORY ${DL_FIELD_INCLUDE_DIRECTORY})

# get DL_FIELD source as external project
include(ExternalProject)

# name for external project
set(DL_FIELD_NAME "DL_FIELD")

# try to convert to absolte full path: when it is a URL, it appears as "${CMAKE_CURRENT_SOURCE_DIR}${DL_FIELD}" and will not be taken as "EXISTS"

# DL_FIELD source location
# if file or directory 
if(EXISTS ${DL_FIELD})

    get_filename_component(DL_FIELD_ABSOLUTE ${DL_FIELD} ABSOLUTE)
    configure_file(dl_field.f90.in dl_field.f90 @ONLY)
# YL 15/07/2019: this will be handled by Python
#    configure_file(dl_f_path.in dl_f_path @ONLY)
    configure_file(dl_field_path.in dl_field_path @ONLY)

    # do not use svn
    set(DL_FIELD_SVN_REPO "")
    set(DL_FIELD_SVN      OFF)
    # set a svn revision number (notice the missing '$'!)
    if(DEFINED ENV{DL_FIELD_SVN_REVISION})
      set(DL_FIELD_SVN_REVISION $ENV{DL_FIELD_SVN_REVISION})
    else()
      set(DL_FIELD_SVN_REVISION "unknown")
    endif()
    # if directory
    if(IS_DIRECTORY ${DL_FIELD})
        # TODO: should be obsolete
        # stop if not absolute path
        if(NOT IS_ABSOLUTE ${DL_FIELD})
            message(FATAL_ERROR "${BoldRed}DL_FIELD_REPO not given in full absolute path. Exiting...${EndColour}")
        endif()
        set(DL_FIELD_DIR     ${DL_FIELD})
        set(DL_FIELD_SRC_DIR ${DL_FIELD}/source)
        set(DL_FIELD_TARBALL "")
    # TODO: support tarball
    # else
    else()
        message(FATAL_ERROR "${BoldRed}Directory expected for DL_FIELD_REPO but file found. Exiting...${EndColour}")
    endif()

    list(APPEND DL_FIELD_HEADER_FILES ${DL_FIELD_SRC_DIR}/convert.h
                                      ${DL_FIELD_SRC_DIR}/dl_field.h
        )

    foreach(DL_FIELD_HEADER ${DL_FIELD_HEADER_FILES})
        if(EXISTS ${DL_FIELD_SRC_DIR}/${DL_FIELD_HEADER})
            file(COPY ${DL_FIELD_SRC_DIR}/${DL_FIELD_HEADER} DESTINATION ${DL_FIELD_INCLUDE_DIRECTORY})
        endif()
    endforeach(DL_FIELD_HEADER)

    # YL 16/11/2023: we are preparing to use DL_FIELD 4.10 but before this is made official
    #                let's keep it optional
    if(EXISTS ${DL_FIELD_SRC_DIR}/ff_fitting.c)
        set(DL_FIELD_FITTING ${DL_FIELD_SRC_DIR}/ff_fitting.c)
    endif()
    if(EXISTS ${DL_FIELD_SRC_DIR}/convert_format.c)
        set(DL_FIELD_CONVERT ${DL_FIELD_SRC_DIR}/convert_format.c)
    endif()

    # select source:
    list(APPEND DL_FIELD_CSOURCES ${DL_FIELD_SRC_DIR}/atom_state.c
                                  ${DL_FIELD_SRC_DIR}/config_mol2.c
                                  ${DL_FIELD_SRC_DIR}/config_pdb.c
                                  ${DL_FIELD_SRC_DIR}/config_xyz.c
                                  ${DL_FIELD_SRC_DIR}/construct.c
                                  ${DL_FIELD_SRC_DIR}/convert.c
                                  ${DL_FIELD_SRC_DIR}/define_molecule.c
                                  ${DL_FIELD_SRC_DIR}/dl_field.c
                                  ${DL_FIELD_SRC_DIR}/dlf_notation.c
                                  ${DL_FIELD_SRC_DIR}/dlf_notation2.c
                                  ${DL_FIELD_SRC_DIR}/dlf_notation_in.c
                                  ${DL_FIELD_FITTING}
                                  ${DL_FIELD_CONVERT}
                                  ${DL_FIELD_SRC_DIR}/energy.c
                                  ${DL_FIELD_SRC_DIR}/make_model.c
                                  ${DL_FIELD_SRC_DIR}/parameter.c
                                  ${DL_FIELD_SRC_DIR}/periodic.c
                                  ${DL_FIELD_SRC_DIR}/structure.c
    )

    # ChemShell/DL_FIELD interface files
    list(APPEND DL_FIELD_CSOURCES "dl_field.f90" "dl_field_routines.f90")

    # setting property GENERATED forces CMake to check dependency
    #set_source_files_properties(${DL_FIELD_CSOURCES} PROPERTIES GENERATED TRUE)

    # FLAGS
    set(CMAKE_SHARED_LINKER_FLAGS "-DOLDALLOC=OFF")

    # SOURCE_DIR is the destination of extraction
    #   BUILD_ALWAYS:
    #   UPDATE_DISCONNECTED: ${DL_FIELD_NO_UPDATE}, supported only after cmake 3.0
    #   URL:                 file://${DL_FIELD_TARBALL}
    ExternalProject_Add(
        ${DL_FIELD_NAME}
        SVN_REPOSITORY      ${DL_FIELD_SVN_REPO}
    #   UPDATE_DISCONNECTED is not working, see: https://cmake.org/Bug/view.php?id=15904
    #    UPDATE_DISCONNECTED ${DL_FIELD_NO_UPDATE}
        PREFIX              ${CHEMSH_ARCH}
        STAMP_DIR           ${CHEMSH_ARCH}/stamp
        TMP_DIR             ${CHEMSH_ARCH}/tmp
        SOURCE_DIR          ${DL_FIELD_DIR}
        CONFIGURE_COMMAND   ""
        BUILD_COMMAND       ${CMAKE_COMMAND} -E cmake_echo_color
                                             --switch=$(COLOR)
                                             --magenta
                                             --bold "Architecture for which '${DL_FIELD_NAME}' is built: '${CHEMSH_ARCH}'"
        INSTALL_COMMAND     ""
    )

    # compile:
    add_library(dl_field SHARED ${DL_FIELD_CSOURCES} ${LINKED})

    if(DEBUG)
        set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "${CHEMSH_C_DEBUG_FLAGS}")
        set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "${CHEMSH_Fortran_DEBUG_FLAGS}")
        if(${CHEMSH_ARCH} STREQUAL "gnu")
            set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "${CHEMSH_C_DEBUG_FLAGS} -O0 -g -ggdb -fbounds-check")
        elseif(${CHEMSH_ARCH} STREQUAL "intel")
            set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "${CHEMSH_C_DEBUG_FLAGS} -O0 -g")
        endif()
    else()
        if(${CHEMSH_ARCH} STREQUAL "gnu")
            set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "-O3 -g -w -ansi -std=c99 -pedantic")
        elseif(${CHEMSH_ARCH} STREQUAL "intel")
            set_target_properties(dl_field PROPERTIES COMPILE_FLAGS "-O3 -g -w -ansi -std=c99 -pedantic")
        endif()
    endif()

    #add_dependencies(dl_field parallel)
    add_dependencies(dl_field ${DL_FIELD_NAME})

else()

    add_library(dl_field SHARED dl_field_dummy.f90 ${NOTLINKED})
    list(APPEND DL_FIELD_CSOURCES "dl_field_dummy.f90")

endif()


target_link_libraries(dl_field dl_py2f)
set_target_properties(dl_field PROPERTIES LINK_FLAGS "-Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map -Wl,--allow-multiple-definition ${CHEMSH_LINK_FLAGS}")

target_include_directories(dl_field PRIVATE ${DL_FIELD_INCLUDE_DIRECTORY})
