#  Copyright (C) 2019 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
# Oct 2019
# Mar 2021 revised

set(PDB2PQR_DEFAULT_VERSION 3.5.2)

include(ExternalProject)

# function to get the PDB2PQR path
function(get_pdb2pqr_dir PDB2PQR)

    # try to convert to absolte full path: when it is a URL, it appears as "${CMAKE_CURRENT_SOURCE_DIR}${PDB2PQR}" and will not be taken as "EXISTS"
    get_filename_component(PDB2PQR_ABSOLUTE "${PDB2PQR}" ABSOLUTE)

    # PDB2PQR source location
    # if file or directory
    if(EXISTS ${PDB2PQR_ABSOLUTE})
        # do not use git
        set(PDB2PQR_GIT_REPO "")
        set(PDB2PQR_GIT      OFF)
        # set a git revision number (notice the missing '$'!)
        if(DEFINED ENV{PDB2PQR_GIT_REVISION})
          set(PDB2PQR_GIT_REVISION $ENV{PDB2PQR_GIT_REVISION})
        else()
          set(PDB2PQR_GIT_REVISION "unknown")
        endif()
        # if directory
        if(IS_DIRECTORY ${PDB2PQR_ABSOLUTE})
            # TODO: should be obsolete
            # stop if not absolute path
            if(NOT IS_ABSOLUTE ${PDB2PQR_ABSOLUTE})
                message(FATAL_ERROR "${BoldRed}PDB2PQR_REPO not given in full absolute path. Exiting...${EndColour}")
            endif()
            set(PDB2PQR_DIR     ${PDB2PQR_ABSOLUTE})
            set(PDB2PQR_SRC_DIR ${PDB2PQR_ABSOLUTE})
            set(PDB2PQR_SRC_DIR ${PDB2PQR_ABSOLUTE} PARENT_SCOPE)
            set(PDB2PQR_TARBALL "")
            set(PDB2PQR_URL     ${PDB2PQR})
        # if file (tar ball)
        else()
            set(PDB2PQR_TARBALL ${PDB2PQR})
            set(PDB2PQR_URL     ${PDB2PQR})
            # YL 05/11/2018: a charm++ name must be analysed for getting a proper WORKING_DIRECTORY during the extraction of the PDB2PQR tarball which should be in theory at the "configure" stage but has to be executed within the "build"-stage ExternalProject_Add(). However at the "build" stage, CMake has NO way to get a returned value from an external script (or even NO way to define an evnvar in the script). Therefore we apply this execute_process() at the "configure" stage.
            # YL 05/11/2018: we have to use `cmake --build dir` because `cmake -P script.cmake` is not allowed to do anything target-related and functions such as ExternalProject_Add() is not scriptable!
            set(PDB2PQR_DIR           ${CHEMSH_DIR}/chemsh/interfaces/pdb2pqr)
            set(PDB2PQR_SRC_DIR       ${PDB2PQR_DIR})
            set(PDB2PQR_SRC_DIR       ${PDB2PQR_DIR} PARENT_SCOPE)
            set(PDB2PQR_BINARY_DIR    ${PDB2PQR_DIR}/${CHEMSH_ARCH}/pdb2pqr)
            file(MAKE_DIRECTORY ${PDB2PQR_BINARY_DIR})
        endif()
    # else: use git repository
    else()
        message("${BoldWhite}PDB2PQR${EndColour} repository URL: ${PDB2PQR}")
        set(PDB2PQR_GIT      ON                            PARENT_SCOPE)
        set(PDB2PQR_GIT_REPO ${PDB2PQR}                    PARENT_SCOPE)
        set(PDB2PQR_GIT_TAG  "v${PDB2PQR_DEFAULT_VERSION}" PARENT_SCOPE)
        set(PDB2PQR_TARBALL  ""                            PARENT_SCOPE)
        set(PDB2PQR_DIR      ${CMAKE_CURRENT_LIST_DIR}/git PARENT_SCOPE)
        set(PDB2PQR_SRC_DIR  ${PDB2PQR_DIR}                PARENT_SCOPE)
        set(PDB2PQR_URL      ""                            PARENT_SCOPE)
        set(PDB2PQR_BUILD_COMMAND ${PYTHON_EXECUTABLE} setup.py build PARENT_SCOPE) # do NOT add quotation marks here!
    endif()

endfunction()

if(NOT DEBUG)
    set(PIP_FLAGS -q)
endif()

if(NOT "${PDB2PQR}" STREQUAL "")
    # FetchContent isn't available until CMake 3.11
# YL 02/10/2020: Ubuntu 18.04 is still with 3.10
#    cmake_minimum_required(VERSION 3.11)
#    include(FetchContent)
    get_pdb2pqr_dir("${PDB2PQR}")
    # cache-level variable cannot be set within a function
    set(PDB2PQR_SRC_DIR "${PDB2PQR_SRC_DIR}" CACHE FILEPATH "" FORCE)

    # get the current pip version
    if(${PIP})
        execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip --version
                        OUTPUT_VARIABLE PIP_VERSION
                        ERROR_QUIET)
    endif()
    string(REGEX MATCH "[0-9]+[.]+[0-9]+([.]?[0-9])?" PIP_VERSION "${PIP_VERSION}")
    # --no-warn-script-location not available until pip v20.0
    if("${PIP_VERSION}" VERSION_GREATER_EQUAL 20.0)
        set(PIP_EXTRA_FLAGS --no-warn-script-location)
    endif()
    if(${PIP})
        message("pip version before upgrading: ${PIP_VERSION}")
    
        # check if --system is available
        execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install --system
                        OUTPUT_VARIABLE PIP_SYSTEM_OUTPUT
                        ERROR_VARIABLE PIP_SYSTEM_ERROR)
        string(FIND ${PIP_SYSTEM_ERROR} "no such option: --system" FOUND_ERROR)
        # --system available
        if("${FOUND_ERROR}" EQUAL -1)
            set(PIP_SYSTEM_FLAGS --system)
        endif()
    endif()

    # YL 10/11/2021: first force an update of pip and numpy (dependency of pandas) so that pip won't try to
    #                uninstall the existing system numpy (which is usually out of date) when installing pandas
    # YL 18/11/2021: we can't install modules with --user because on some weird systems such as A* the compute nodes can't access $HOME/.local
    message("Setting environment variable PYTHONUSERBASE to ${CHEMSH_DIR}/build")
    set(ENV{PYTHONUSERBASE} ${CHEMSH_DIR}/build)
    if(${PIP})
        execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check --user --upgrade ${PIP_EXTRA_FLAGS} pip)
    # YL 11/11/2021: let's manually install the pandas dependencies so that we can use --no-deps below
    #                requests is a PDB2PQR dependency
# YL 11/04/2022: no longer required
#    execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install --user --upgrade ${PIP_EXTRA_FLAGS} launchpadlib testresources)
#    execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install --user --upgrade ${PIP_EXTRA_FLAGS} pytz python-dateutil six requests)
        execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check --user --upgrade ${PIP_EXTRA_FLAGS} docutils propka requests)
        execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check --user --upgrade ${PIP_EXTRA_FLAGS} numpy)
    endif()
# YL 11/04/2022: since v3.2.0 pandas became no longer a dependency, reported by HMS
#    # pandas
#    execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import pandas; print(pandas.__version__)"
#                    OUTPUT_VARIABLE PANDAS_VERSION
#                    ERROR_QUIET)
#    if("${PANDAS_VERSION}" STREQUAL "")
#        message("Installing missing PDB2PQR dependency pandas...")
#        # YL 12/05/2021: use --system to prevent --user as some versions throw out an error that --user and --prefix
#        #                can't be used at the same time (but I didn't use --user at all!)
#        # YL 11/11/2021: use --no-deps to prevent pip uninstalling old versions of NumPy
#        if("${PYTHON_VERSION_MINOR}" STREQUAL "6")
#            # YL 11/11/2021: the minimal version of pandas required by the current PDB2PQR 3.1 is only 1.0
#            #                so let's install a 1.0.5 which needs NumPy>=1.13 so that some systems (SCARF) with
#            #                old system NumPy can also run
#            message("Command: ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install --user pandas==1.0.5 --no-deps")
#            execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install --user pandas==1.0.5 --no-deps)
#        else()
#            message("Command: ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install ${PIP_SYSTEM_FLAGS} --user pandas==1.0.5 --no-deps")
#            execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip ${PIP_FLAGS} --disable-pip-version-check install ${PIP_SYSTEM_FLAGS} --user pandas==1.0.5 --no-deps)
#        endif()
#    endif()
    # install the PDB2PQR dependencies: mmcif_pdbx 
    execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import pdbx; print(pdbx.__version__)"
                    OUTPUT_VARIABLE PDBX_VERSION
                    ERROR_QUIET)
    if("${PDBX_VERSION}" STREQUAL "" AND ${PIP})
        message("Installing missing PDB2PQR dependency mmcif_pdbx...")
        if("${PYTHON_VERSION_MINOR}" STREQUAL "6")
            message("Command: ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check --user --upgrade mmcif_pdbx")
            execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check --user --upgrade mmcif_pdbx)
        else()
            message("Command: ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check  ${PIP_SYSTEM_FLAGS} --user --upgrade mmcif_pdbx")
            execute_process(COMMAND ${PYTHON_EXECUTABLE} -m pip install ${PIP_FLAGS} --disable-pip-version-check ${PIP_SYSTEM_FLAGS} --user --upgrade mmcif_pdbx)
        endif()
    endif()

else()
    return()
endif()

# get the PDB2PQR version
string(REGEX MATCH "([0-9]*[.])+([0-9]*[.])+[0-9]+" PDB2PQR_VERSION "${PDB2PQR}")
if("${PDB2PQR_VERSION}" STREQUAL "")
    set(PDB2PQR_VERSION ${PDB2PQR_DEFAULT_VERSION})
endif()
set(PDB2PQR_NAME pdb2pqr-${PDB2PQR_VERSION})

# SOURCE_DIR is the destination of extraction
#   BUILD_ALWAYS:
#   UPDATE_DISCONNECTED: ${PDB2PQR_NO_UPDATE}, supported only after cmake 3.0
#   URL:                 file://${PDB2PQR_TARBALL}
#    UPDATE_COMMAND      git pull --allow-unrelated-histories ${PDB2PQR_GIT_REPO}
if(NOT TARGET pdb2pqr)
    set(PDB2PQR_RECOMPILE YES)
endif()

# Supported compilers: clang craycc gcc gcc3 icc icc8 iccstatic mpicxx pathscale pgcc xlc xlc64
# Supported options: bigemulator bigsim causalft cuda g95 gfortran gm gm2 ifort lam lcs mic mlogft mpt ooc papi persistent pgf90 pthreads scyld smp syncft tsan
if(${CHEMSH_ARCH} STREQUAL "intel")
    set(PDB2PQR_ARCH Linux-x86_64-icc)
    set(PDB2PQR_C_COMPILER   "icc -fPIC -m64 -O3 -D__PURE_INTEL_C99_HEADERS__")
    set(PDB2PQR_C_FLAGS      "-diag-enable=power")
    set(PDB2PQR_CXX_FLAGS    "-diag-enable=power")
    set(PDB2PQR_CXX_COMPILER "${CMAKE_CXX_COMPILER} -fPIC -m64 -std=c++0x -O3 -D__PURE_INTEL_C99_HEADERS__")
elseif(${CHEMSH_ARCH} STREQUAL "gnu")
    set(PDB2PQR_ARCH Linux-x86_64-g++)
    set(PDB2PQR_C_COMPILER "$gcc -fPIC -m64 -O3")
    set(PDB2PQR_C_FLAGS    "-fexpensive-optimizations -ffast-math")
    set(PDB2PQR_CXX_COMPILER "${CMAKE_CXX_COMPILER} -fPIC -m64 -std=c++0x -O3")
    set(PDB2PQR_CXX_FLAGS    "-fexpensive-optimizations -ffast-math")
endif()

ExternalProject_Add(
    ${PDB2PQR_NAME}
    PREFIX              ${CMAKE_CURRENT_SOURCE_DIR}
    STAMP_DIR           stamp
    TMP_DIR             tmp
    DOWNLOAD_DIR        download
    SOURCE_DIR          src
    URL                 ${PDB2PQR_URL}
    GIT_REPOSITORY      ${PDB2PQR_GIT_REPO}
    GIT_TAG             ${PDB2PQR_GIT_TAG}
    GIT_SHALLOW         1
    GIT_PROGRESS        ${DEBUG}
    GIT_CONFIG          advice.detachedHead=false
    TIMEOUT             600
    DOWNLOAD_NO_PROGRESS YES
    CONFIGURE_COMMAND   ""
    BUILD_COMMAND       "${PDB2PQR_BUILD_COMMAND}"
    BUILD_IN_SOURCE     YES # important to prevent looking for directory PDB2PQR-build
    BUILD_ALWAYS        NO
    INSTALL_COMMAND     ""
    WORKING_DIRECTORY   src
)

set(PDB2PQR_OBJ_DIR ${PDB2PQR_SRC_DIR}/${PDB2PQR_ARCH}/obj)


set_directory_properties(PROPERTIES
    ADDITIONAL_MAKE_CLEAN_FILES "CMakeFiles;Makefile;cmake_install.cmake;download;src;stamp;tmp;__pycache__;"
)
