#  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/>.

# Build the ChemShell executable with libraries from the subdirectories
#set(CMAKE_C_COMPILER $ENV{CC})

# determine $PYTHONPATH according to source files path (rather than the executable path!)
# for use with chemsh wrapper script
get_filename_component(CHEMSH_PYTHONPATH ${CMAKE_CURRENT_SOURCE_DIR}/../.. ABSOLUTE)

# set directory for output of executable
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CHEMSH_DIR}/bin/${CHEMSH_ARCH})
#set(CMAKE_Fortran_MODULE_DIRECTORY ../modules/${CHEMSH_ARCH})

# parallel or serial
# YL 10/03/2021: to redeem the readibility in main.c we split them into two files and abandon using preprocessors
if(${WITH_MPI})
    set(CHEMSH_C_MAIN_SOURCE main_parallel.c)
    add_definitions(-DMPI)
    set(CHEMSH_PARALLEL_LIB parallel)
    # for chemsh wrapper script
    set(CHEMSH_EXECUTION_MODE mpi)
else()
    set(CHEMSH_C_MAIN_SOURCE main_serial.c)
    add_definitions(-DMPI)
    set(MPIEXEC "")
    set(CHEMSH_PARALLEL_LIB "")
    # for chemsh wrapper script
    set(CHEMSH_EXECUTION_MODE serial) 
endif()

# Generate the chemsh wrapper script in bin/
# CHEMSH_EXECUTABLE is replaced at compile time in chemsh_script.in
set(CHEMSH_EXECUTABLE ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/chemsh.x)
# break into new lines
foreach(LINE ${CHEMSH_BASH_HEADER_BUFF})
    set(CHEMSH_BASH_HEADER "${CHEMSH_BASH_HEADER}${LINE}\n")
endforeach()
foreach(LINE ${CHEMSH_BASH_FOOTER_BUFF})
    set(CHEMSH_BASH_FOOTER "${CHEMSH_BASH_FOOTER}${LINE}\n")
endforeach()
configure_file(chemsh.in chemsh @ONLY)
configure_file(chemsh_app.py.in chemsh_app.py @ONLY)
#configure_file(chemsh_script.in ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/chemsh.sh.ARCHIVE @ONLY)

# generate CHEM_ARCH at compile time to allow coexistence of builds for different compiler architectures
# FIXME: gfortran issues warnings about the 4th and 5th lines
# YL 18/02/2023: @PYTHONPATH@ can't take the environment variable directly and needs an intermediate variable
set(PYTHONPATH "$ENV{PYTHONPATH}")
configure_file(chemsh_consts.c.in ${CHEMSH_BUILD_DIR}/modules/chemsh_consts.c @ONLY)

# compile and link
#${CPARALLEL_SOURCES}
add_executable(chemsh.x ${CHEMSH_C_MAIN_SOURCE}
                        initpy.c
                        register.c
                        chemsh.f90
                        args.f90
                        ${CHEMSH_BUILD_DIR}/modules/chemsh_consts.c
              )

# link
# TODO: use a global variable to replace "gulp nwchem gamess_uk lsdalton"
list(APPEND CHEMSH_LIBS ${Python3_LIBRARIES} ${CHEMSH_PARALLEL_LIB} castep cp2k dl_field dl_monte dl_poly fhiaims gamess-uk gulp lsdalton nwchem)
target_link_libraries(chemsh.x ${CHEMSH_LIBS})

# -D_Float128=__float128 fixes the incompatability between  icc 17 and gcc 7:
# https://software.intel.com/en-us/forums/intel-c-compiler/topic/742701
# should be already fixed in Intel 18.01
#set_target_properties(chemsh.x PROPERTIES COMPILE_FLAGS "${CMAKE_Fortran_FLAGS}")

# ${CHEMSH_INTEL_MKL_BLACS_FLAGS} is required by GA only on ARCHER
if(${CHEMSH_ARCH} STREQUAL "intel")
    # YL 18/02/2018: use -shared-intel to prevent
    #     ld: ..../bin/intel/chemsh.x: hidden symbol `__intel_cpu_features_init' in /opt/intel/lib/intel64/libirc.a(cpu_feature_disp.o) is referenced by DSO
    #     ld: final link failed: Bad value
    set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "-Wl,--unresolved-symbols=report-all \
                                                          -Wl,--start-group                   \
                                                          ${CHEMSH_PLATFORM_FLAGS}            \
                                                          -Wl,--end-group                     \
                                                          -shared-intel                       \
                                                          -Wl,--unresolved-symbols=ignore-all \
                                                          -Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map \
							  ${CHEMSHX_LINK_FLAGS}"
                         )
elseif(${CHEMSH_ARCH} STREQUAL "cray")
    # YL 18/02/2018: use -shared-intel to prevent
    #     ld: ..../bin/intel/chemsh.x: hidden symbol `__intel_cpu_features_init' in /opt/intel/lib/intel64/libirc.a(cpu_feature_disp.o) is referenced by DSO
    #     ld: final link failed: Bad value
    set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "-Wl,--unresolved-symbols=report-all \
                                                          -Wl,-rpath -Wl,${CHEMSH_LD_LIBRARY_PATH} \
                                                          -Wl,--start-group                   \
                                                          ${CHEMSH_PLATFORM_FLAGS}            \
                                                          -Wl,--end-group                     \
                                                          -Wl,--unresolved-symbols=ignore-all \
                                                          -Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map \
							  ${CHEMSHX_LINK_FLAGS}"
                         )
elseif(${CHEMSH_ARCH} STREQUAL "cpe-gnu")
    set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "-Wl,--unresolved-symbols=report-all \
                                                          -Wl,-rpath -Wl,${CHEMSH_LD_LIBRARY_PATH} \
                                                          -Wl,--start-group                   \
                                                          ${CHEMSH_PLATFORM_FLAGS}            \
                                                          -Wl,--end-group                     \
                                                          -Wl,--version-script=${CMAKE_CURRENT_LIST_DIR}/export.map \
							  ${CHEMSHX_LINK_FLAGS}"
                         )
elseif(${CHEMSH_ARCH} STREQUAL "gnu")
    set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "${CHEMSHX_LINK_FLAGS}")
endif()

# install() command does not work
# install(FILES chemsh.py DESTINATION /home/tsz53383)
file(INSTALL chemsh
     DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}
     FILE_PERMISSIONS OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
     NO_SOURCE_PERMISSIONS)


#        PERMISSIONS OWNER_EXECUTE GROUP_EXECUTE WORLD_EXECUTE)
#set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_Fortran_FLAGS}")
#set_target_properties(chemsh.x PROPERTIES LINK_FLAGS "--entry main")
        #DESTINATION ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}


# YL: do NOT delete
# TWK: pythonpath hack no longer required - use chemsh wrapper script instead
#file(WRITE ../modules/${CHEMSH_ARCH}/pythonpath.c "
#\#include <stdlib.h>
#\#include <string.h>
#char *get_pythonpath() {
#    const char *buff = \"${CHEMSH_PYTHONPATH}\";
#    const int len = strlen(buff);
#    char *pythonpath = (char *) malloc(sizeof(char)*(len+1));
#    int i;
#    for (i=0; i<len; ++i) {
#        pythonpath[i] = buff[i];
#    }
#    pythonpath[len] = *\"\\0\";
#    return pythonpath;
#}")

