# - musrfit
cmake_minimum_required(VERSION 3.17)

# cmake: use BoostConfig.cmake instead of FindBoost.
# CMP0167 only exists since cmake 3.30, hence guard with 'if (POLICY ...)'.
# A version comparison must not be used here: 'CMAKE_VERSION GREATER_EQUAL 3.30'
# is a *numeric* comparison and would wrongly fire on e.g. cmake 3.20.
if (POLICY CMP0167)
  cmake_policy(SET CMP0167 NEW)
endif ()

project(musrfit VERSION 1.12.2 LANGUAGES C CXX)

#--- needed to compile PMacDockIcon.mm (sets the musrview/musrFT/musrt0 Dock icon
#--- via Cocoa, since TGCocoa's X11-style icon/class hints are no-ops on macOS)
if (APPLE)
  enable_language(OBJCXX)
endif (APPLE)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

set(CMAKE_INSTALL_LIBDIR lib CACHE PATH "Object code libraries")
include(GNUInstallDirs)

#--- XDG data directory for .desktop files and icons (Linux only) -------------
#--- desktops only look for them in $XDG_DATA_HOME (~/.local/share) and
#--- $XDG_DATA_DIRS (/usr/local/share:/usr/share), hence a non-standard prefix
#--- (e.g. $ROOTSYS) cannot be used for them.
if (UNIX AND NOT APPLE)
  if (CMAKE_INSTALL_PREFIX STREQUAL "/usr" OR CMAKE_INSTALL_PREFIX STREQUAL "/usr/local")
    set(xdg_datadir_default "${CMAKE_INSTALL_FULL_DATADIR}")
  elseif (CMAKE_INSTALL_PREFIX MATCHES "^$ENV{HOME}/")
    set(xdg_datadir_default "$ENV{HOME}/.local/share")
  else ()
    set(xdg_datadir_default "/usr/local/share")
  endif ()
  set(MUSRFIT_XDG_DATA_DIR "${xdg_datadir_default}" CACHE PATH
      "where the .desktop files and icons are installed (must be in the XDG search path)")
endif (UNIX AND NOT APPLE)

#--- musrfit specific options -------------------------------------------------
option(nexus "build optional NeXus support. Needed for ISIS" OFF)
#--- 'HAVE_HDF4' is the name the C++ sources (PNeXus, PRunDataHandler,
#--- dump_header, musrfit) and src/external/nexus/CMakeLists.txt already use,
#--- hence keep it for the option as well.
option(HAVE_HDF4 "in addition to HDF5, support the older HDF4 based NeXus files. Requires -Dnexus=1" OFF)
option(ASlibs "build optional ASlibs" OFF)
option(BMWlibs "build optional BMWlibs" OFF)
option(BNMRlibs "build optional beta-NMR libs" OFF)
option(DummyUserFcn "build optional dummy user function" OFF)
option(qt_based_tools "try to install Qt based tools (musredit, musrWiz, musrStep, mupp)" ON)
option(try_OpenMP "try to use OpenMP if available" ON)
# define qt_version with possible values 'auto' or version '3', '4', '5', '6'
set(qt_version AUTO CACHE STRING "provide a specific Qt version to be used.")
set_property(CACHE qt_version PROPERTY STRINGS AUTO 3 4 5 6)

#--- set a default build type if none was specified ---------------------------
set(default_build_type "Release")

if (NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  message(STATUS "Setting build type to '${default_build_type}' as none was specified.")
  set(CMAKE_BUILD_TYPE "${default_build_type}" CACHE
      STRING "Choose the type of build." FORCE)
  # Set the possible values of build type for cmake-gui
  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
    "Debug" "Release" "MinSizeRel" "RelWithDebInfo")
endif ()

#--- perform some checks and generate the config.h ----------------------------

#--- the next line is needed that the math functions are found ----------------
#--- (CMAKE_REQUIRED_INCLUDES expects *directories*, not header names, hence
#---  it must not be used here.)
set(CMAKE_REQUIRED_LIBRARIES m)

include(CheckTypeSize)
include(CheckIncludeFiles)
include(CheckFunctionExists)
check_include_files(alloca.h HAVE_ALLOCA_H)
check_include_files("sys/ipc.h;sys/shm.h" HAVE_SHMGET)
check_include_files(dlfcn.h HAVE_DLFCN_H)
check_function_exists(erf HAVE_ERF)
check_function_exists(getloadavg HAVE_GETLOADAVG)
check_include_files(inttypes.h HAVE_INTTYPES_H)
check_include_files(memory.h HAVE_MEMORY_H)
check_function_exists(powl HAVE_POWL)
check_include_files(memory.h HAVE_MEMORY_H)
check_include_files(stdint.h HAVE_STDINT_H)
check_include_files(stdlib.h HAVE_STDLIB_H)
check_include_files(string.h HAVE_STRING_H)
check_include_files(strings.h HAVE_STRINGS_H)
check_include_files(sys/stat.h HAVE_SYS_STAT_H)
check_include_files(sys/types.h HAVE_SYS_TYPES_H)
check_include_files(sys/unistd.h HAVE_UNISTD_H)
check_type_size("long double" LONG_DOUBLE)
check_type_size("double" DOUBLE)
if (${LONG_DOUBLE} GREATER ${DOUBLE})
  set(HAVE_LONG_DOUBLE 1)
  set(HAVE_LONG_DOUBLE_WIDER 1)
endif (${LONG_DOUBLE} GREATER ${DOUBLE})

#--- do not leak the check settings into the find_package() calls below --------
unset(CMAKE_REQUIRED_LIBRARIES)

#--- check for all the needed packages ----------------------------------------

#--- add path to my own find modules and other stuff
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)

#--- check for pkg-config -----------------------------------------------------
find_package(PkgConfig REQUIRED)

#--- check for git ------------------------------------------------------------
find_package(Git REQUIRED)

#--- check for ROOT -----------------------------------------------------------
#--- remember the compiler flags *before* ROOT's recommended flags are added,
#--- so that the Qt applications, which do not use ROOT at all, can go back to
#--- them (see src/musredit_qt6/CMakeLists.txt) --------------------------------
set(MUSRFIT_CXX_FLAGS_NO_ROOT "${CMAKE_CXX_FLAGS}")

find_package(ROOT 6.18 REQUIRED COMPONENTS Gui MathMore Minuit2 XMLParser)

#--- Deliberately NOT 'include(${ROOT_USE_FILE})' here. That file
#---   - overwrites CMAKE_CXX_STANDARD with ROOT's value, silently discarding
#---     the setting made at the top of this file,
#---   - calls link_directories(), which is not needed since ROOT_LIBRARIES
#---     holds absolute library paths, and
#---   - adds ROOT's include dirs / flags / definitions to *every* target of
#---     the project, including the Qt applications.
#--- ROOT itself states that CMAKE_CXX_FLAGS should not be touched, the flags
#--- are only a recommendation. ROOTConfig.cmake already pulls in
#--- RootMacros.cmake, i.e. root_generate_dictionary() is available. The guard
#--- below is only there for ROOT versions which might not do so.
if (NOT COMMAND root_generate_dictionary)
  include("${ROOT_CMAKE_DIR}/RootMacros.cmake")
endif ()

#--- Since ROOT 6.40 root_generate_dictionary(... MODULE ...) implicitly adds
#--- 'Core' to the DEPENDS of the rootcling custom command. Within ROOT's own
#--- build that is a target, in an external project it is not (only ROOT::Core
#--- exists), hence make would look for a file 'Core' in the current binary
#--- dir ("No rule to make target 'src/classes/Core'"). Provide the plain name
#--- as an alias of ROOT::Core. An alias of an imported target has to be global
#--- with CMake < 3.18. ---------------------------------------------------------
if (TARGET ROOT::Core AND NOT TARGET Core)
  set_target_properties(ROOT::Core PROPERTIES IMPORTED_GLOBAL TRUE)
  add_library(Core ALIAS ROOT::Core)
endif ()

#--- ROOT headers have to be compiled with at least the C++ standard ROOT was
#--- built with, otherwise the ABI does not match. Raise ours if needed, but
#--- never silently lower it. --------------------------------------------------
if (ROOT_CXX_STANDARD AND ROOT_CXX_STANDARD GREATER CMAKE_CXX_STANDARD)
  message(STATUS "ROOT was built with C++${ROOT_CXX_STANDARD}, raising CMAKE_CXX_STANDARD accordingly.")
  set(CMAKE_CXX_STANDARD ${ROOT_CXX_STANDARD})
endif ()

#--- ROOT's recommended compiler flags. Some of them are ABI relevant when
#--- ROOT headers are used, e.g. -fsigned-char (char is unsigned by default on
#--- aarch64) and -fsized-deallocation, hence they are kept for everything that
#--- talks to ROOT. --------------------------------------------------------
include_directories(SYSTEM ${ROOT_INCLUDE_DIRS})
add_definitions(${ROOT_DEFINITIONS})
string(APPEND CMAKE_CXX_FLAGS " ${ROOT_CXX_FLAGS}")
string(APPEND CMAKE_C_FLAGS " ${ROOT_C_FLAGS}")

#--- the next check is need to set a flag, since root 6.24 (minuit2) breaks
#--- the backwards compatibility. ---------------------------------------------
if (ROOT_VERSION VERSION_LESS "6.23")
  set(ROOT_GRTEQ_24 0)
else ()
  set(ROOT_GRTEQ_24 1)
endif ()
set(ROOT_GRTEQ_24 ${ROOT_GRTEQ_24} CACHE INTERNAL "ROOT Version check")

#--- check for boost ----------------------------------------------------------
find_package(Boost QUIET)
if (Boost_VERSION VERSION_GREATER_EQUAL "1.89")
  find_package(Boost REQUIRED COMPONENTS filesystem)
  set(BOOST_LINK_LIBS Boost::filesystem)
else (Boost_VERSION VERSION_GREATER_EQUAL "1.89")
  find_package(Boost REQUIRED COMPONENTS system filesystem)
  set(BOOST_LINK_LIBS Boost::filesystem Boost::system)
endif (Boost_VERSION VERSION_GREATER_EQUAL "1.89")
message(STATUS "Boost libs: ${Boost_LIBRARIES}")

#--- check for gsl ------------------------------------------------------------
find_package(GSL REQUIRED)

#--- check for fftw3 ----------------------------------------------------------
find_package(FFTW3 REQUIRED)

#--- check for libxml2 --------------------------------------------------------
find_package(LibXml2 REQUIRED)

#--- check whether <filesystem> needs an extra library to link ----------------
#--- On most current toolchains (gcc>=9, clang/libc++, MSVC, macOS) std::filesystem
#--- lives in the main runtime library and just works. On gcc-8 (e.g. RHEL8's
#--- system gcc, 8.5) it is present but still split out into a separate static
#--- archive, libstdc++fs.a, and needs an explicit -lstdc++fs, otherwise linking
#--- fails with 'undefined reference to std::filesystem::remove(...)' etc.
#--- Detected via an actual compile+link try, so this adapts automatically
#--- instead of guessing from compiler/OS name and risks affecting unrelated
#--- platforms. -----------------------------------------------------------
include(CheckCXXSourceCompiles)
set(STDFS_TEST_SRC "
#include <filesystem>
int main() {
  std::filesystem::path p(\"foo\");
  std::error_code ec;
  std::filesystem::remove(p, ec);
  return 0;
}
")
check_cxx_source_compiles("${STDFS_TEST_SRC}" HAVE_STD_FILESYSTEM_NOLIB)

set(STDFS_LIBRARY "")
if (NOT HAVE_STD_FILESYSTEM_NOLIB)
  foreach (_stdfs_lib stdc++fs c++fs)
    set(CMAKE_REQUIRED_LIBRARIES ${_stdfs_lib})
    unset(HAVE_STD_FILESYSTEM_WITH_${_stdfs_lib} CACHE)
    check_cxx_source_compiles("${STDFS_TEST_SRC}" HAVE_STD_FILESYSTEM_WITH_${_stdfs_lib})
    unset(CMAKE_REQUIRED_LIBRARIES)
    if (HAVE_STD_FILESYSTEM_WITH_${_stdfs_lib})
      set(STDFS_LIBRARY ${_stdfs_lib})
      break ()
    endif ()
  endforeach ()
  if (NOT STDFS_LIBRARY)
    message(FATAL_ERROR "std::filesystem is required but no linkable implementation could be found")
  endif ()
  message(STATUS "std::filesystem needs extra library: ${STDFS_LIBRARY}")
endif ()

#--- check for OpenMP ---------------------------------------------------------
if (try_OpenMP)
  #--- AppleClang has no built-in OpenMP runtime; MacPorts' 'libomp' port
  #--- nests its headers/library one level deeper (include/libomp, lib/libomp)
  #--- than the <prefix>/include, <prefix>/lib layout FindOpenMP.cmake looks
  #--- for by default, so point it there directly if the port is installed. -
  #--- (Only takes effect if the user hasn't already set OpenMP_ROOT.) ------
  if (APPLE AND NOT DEFINED OpenMP_ROOT AND EXISTS "/opt/local/lib/libomp")
    set(OpenMP_ROOT "/opt/local/lib/libomp" CACHE PATH "OpenMP root directory")
  endif ()
  if (APPLE AND EXISTS "/opt/local/include/libomp")
    list(APPEND CMAKE_PREFIX_PATH "/opt/local/include/libomp")
  endif ()
  find_package(OpenMP)
  if (OpenMP_CXX_FOUND)
    add_compile_definitions(HAVE_GOMP)
    set(HAVE_GOMP 1 CACHE INTERNAL "Have GOMP")
  endif (OpenMP_CXX_FOUND)
endif (try_OpenMP)

#--- check for Qt -------------------------------------------------------------
if (qt_based_tools)
  #--- MacPorts installs the actual Qt6 tree, including its CMake package
  #--- config files, under libexec/qt6 rather than directly under lib/cmake,
  #--- so find_package(Qt6...) below would not see it otherwise. ------------
  if (APPLE AND EXISTS "/opt/local/libexec/qt6/lib/cmake")
    list(APPEND CMAKE_PREFIX_PATH "/opt/local/libexec/qt6/lib/cmake")
  endif ()
  # check for any Qt, i.e. AUTO
  if (qt_version STREQUAL AUTO)
    # try Qt6
    find_package(Qt6Core QUIET)
    if (Qt6Core_FOUND)
      find_package(Qt6Widgets CONFIG REQUIRED)
      find_package(Qt6Xml CONFIG REQUIRED)
      find_package(Qt6Network CONFIG REQUIRED)
      find_package(Qt6Svg CONFIG REQUIRED)
      find_package(Qt6PrintSupport CONFIG REQUIRED)
    endif (Qt6Core_FOUND)
    # try Qt5
    if (NOT Qt6Core_FOUND)
      find_package(Qt5Core QUIET)
      if (Qt5Core_FOUND)
        find_package(Qt5Widgets CONFIG REQUIRED)
        find_package(Qt5Xml CONFIG REQUIRED)
        find_package(Qt5Network CONFIG REQUIRED)
        find_package(Qt5Svg CONFIG REQUIRED)
        find_package(Qt5PrintSupport CONFIG REQUIRED)
      endif (Qt5Core_FOUND)
    endif (NOT Qt6Core_FOUND)

    # if Qt6 and Qt5 is not found, try Qt4
    if (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND)
      find_package(Qt4 COMPONENTS QtGui QtWebKit QtXml)
    endif (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND)

    # if Qt6, Qt5 and Qt4 is not found try Qt3. Hopefully you never reach this point
    if (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND AND NOT Qt4_FOUND)
      find_package(Qt3)
    endif (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND AND NOT Qt4_FOUND)
  endif (qt_version STREQUAL AUTO)

  # check specifically for Qt6
  if (qt_version STREQUAL 6)
    find_package(Qt6Core)
    if (Qt6Core_FOUND)
      find_package(Qt6Widgets CONFIG REQUIRED)
      find_package(Qt6Xml CONFIG REQUIRED)
      find_package(Qt6Network CONFIG REQUIRED)
      find_package(Qt6Svg CONFIG REQUIRED)
      find_package(Qt6PrintSupport CONFIG REQUIRED)
    else (Qt6Core_FOUND)
      message(FATAL_ERROR "Couldn't find the specifically requested Qt6 version.")
    endif (Qt6Core_FOUND)
  endif (qt_version STREQUAL 6)

 # check specifically for Qt5
  if (qt_version STREQUAL 5)
    find_package(Qt5Core)
    if (Qt5Core_FOUND)
      find_package(Qt5Widgets CONFIG REQUIRED)
      find_package(Qt5Xml CONFIG REQUIRED)
      find_package(Qt5Network CONFIG REQUIRED)
      find_package(Qt5Svg CONFIG REQUIRED)
      find_package(Qt5PrintSupport CONFIG REQUIRED)
    else (Qt5Core_FOUND)
      message(FATAL_ERROR "Couldn't find the specifically requested Qt5 version.")
    endif (Qt5Core_FOUND)
  endif (qt_version STREQUAL 5)

  # check specifically for Qt4
  if (qt_version STREQUAL 4)
    find_package(Qt4 COMPONENTS QtGui QtWebKit QtXml)
    if (NOT Qt4_FOUND)
      message(FATAL_ERROR "Couldn't find the specifically requested Qt4 version.")
    endif (NOT Qt4_FOUND)
  endif (qt_version STREQUAL 4)

  # check specifically for Qt3
  if (qt_version STREQUAL 3)
    find_package(Qt3)
    if (NOT QT_FOUND)
      message(FATAL_ERROR "Couldn't find the specifically requested Qt3 version.")
    endif (NOT QT_FOUND)
  endif (qt_version STREQUAL 3)
endif (qt_based_tools)

#--- if NeXus check also for HDF4 (optional), HDF5 ----------------------------
if (HAVE_HDF4 AND NOT nexus)
  message(WARNING "HAVE_HDF4 only has an effect together with -Dnexus=1, it will be ignored.")
endif ()

if (nexus)
  find_package(HDF5 COMPONENTS CXX REQUIRED)
  if (HAVE_HDF4)
    #--- check for HDF4 -----------------------------------------------------------
    # Find HDF4 manually (pkg-config often doesn't have hdf4). In addition to the
    # standard system locations, also look under /usr/local/hdf4 and /opt/local
    # (MacPorts), which are common self-built/ported install prefixes and are not
    # part of CMake's default search path. HDF4 built with its own CMake build
    # system (as opposed to the autotools build) names the low-level library
    # 'hdf' instead of 'df', so both names are accepted.
    find_path(HDF4_INCLUDE_DIR
      NAMES mfhdf.h
      HINTS /usr/local/hdf4/include /opt/local/include/hdf
      PATH_SUFFIXES hdf
    )

    find_library(HDF4_DF_LIBRARY
      NAMES df libdf hdf libhdf
      HINTS /usr/local/hdf4/lib /opt/local/lib
    )

    find_library(HDF4_MFHDF_LIBRARY
      NAMES mfhdf libmfhdf
      HINTS /usr/local/hdf4/lib /opt/local/lib
    )

    if (HDF4_INCLUDE_DIR AND HDF4_DF_LIBRARY AND HDF4_MFHDF_LIBRARY)
      set(HDF4_FOUND TRUE)
      set(HDF4_INCLUDE_DIRS ${HDF4_INCLUDE_DIR})
      set(HDF4_LIBRARIES ${HDF4_MFHDF_LIBRARY} ${HDF4_DF_LIBRARY})
      message(STATUS "Found HDF4: ${HDF4_INCLUDE_DIR}")
      message(STATUS "  HDF4 libraries: ${HDF4_LIBRARIES}")
    else()
      message(FATAL_ERROR "HDF4 library not found. Please install libhdf4-dev or hdf-devel")
    endif()

    #--- try to extract the HDF4 version from H4config.h (autotools builds) --------
    # Some distributions (e.g. Debian/Ubuntu's libhdf4-dev) install it lower-cased
    # as 'h4config.h' instead of the upstream 'H4config.h', so check both.
    if (EXISTS "${HDF4_INCLUDE_DIR}/H4config.h")
      set(HDF4_CONFIG_HEADER "${HDF4_INCLUDE_DIR}/H4config.h")
    elseif (EXISTS "${HDF4_INCLUDE_DIR}/h4config.h")
      set(HDF4_CONFIG_HEADER "${HDF4_INCLUDE_DIR}/h4config.h")
    endif ()
    if (HDF4_CONFIG_HEADER)
      file(STRINGS "${HDF4_CONFIG_HEADER}" HDF4_VERSION_LINE REGEX "^#define[ \t]+H4_VERSION[ \t]+\"[^\"]*\"")
      string(REGEX REPLACE "^#define[ \t]+H4_VERSION[ \t]+\"([^\"]*)\".*" "\\1" HDF4_VERSION "${HDF4_VERSION_LINE}")
    endif ()

    # HDF4 4.4.0 changed the Vgetname() prototype from
    #   int32 Vgetname(int32 vkey, char *vgname)
    # to
    #   int32 Vgetname(int32 vkey, char *vgname, size_t *buf_size)
    # (a fix for a buffer-overflow issue). Detect which one is present so
    # PNeXus.cpp can call the right form for both old and new HDF4 releases.
    include(CheckCXXSourceCompiles)
    set(CMAKE_REQUIRED_INCLUDES ${HDF4_INCLUDE_DIRS})
    set(CMAKE_REQUIRED_LIBRARIES ${HDF4_LIBRARIES})
    check_cxx_source_compiles("
      #include <mfhdf.h>
      int main() {
        int32 vkey = 0;
        char name[64];
        size_t buf_size = sizeof(name);
        Vgetname(vkey, name, &buf_size);
        return 0;
      }
    " HDF4_VGETNAME_HAS_BUFSIZE)
    unset(CMAKE_REQUIRED_INCLUDES)
    unset(CMAKE_REQUIRED_LIBRARIES)

    if (HDF4_VGETNAME_HAS_BUFSIZE)
      add_compile_definitions(HDF4_VGETNAME_HAS_BUFSIZE)
    endif (HDF4_VGETNAME_HAS_BUFSIZE)

    add_compile_definitions(HAVE_HDF4)
  endif (HAVE_HDF4)
  add_compile_definitions(PNEXUS_ENABLED)
endif (nexus)

#--- check for Cuba lib if BMWlibs are enabled --------------------------------
#//as35 probably always stick to the internal one ...

#--- all checks done -> feed config.h -----------------------------------------
set(HAVE_CONFIG_H 1 CACHE INTERNAL "config.h is available")
configure_file(${CMAKE_SOURCE_DIR}/cmake/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h)

#--- check if project source is a git repo ------------------------------------
if (EXISTS "${CMAKE_SOURCE_DIR}/.git/HEAD")
  message(STATUS "is a git repo")
  set(IS_GIT_REPO 1)
else ()
  message(STATUS "is NOT a git repo")
  set(IS_GIT_REPO 0)
endif ()

#--- start create git-revision.h ----------------------------------------------
if (IS_GIT_REPO)
  add_custom_target(git_revision ALL
    COMMAND sh ${CMAKE_SOURCE_DIR}/src/git_revision.sh ${CMAKE_BINARY_DIR}/src
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
    COMMENT "Checking git revision"
  )

  set(HAVE_GIT_REV_H "-DHAVE_GIT_REV_H")
else (IS_GIT_REPO)
  set(HAVE_GIT_REV_H "")
endif (IS_GIT_REPO)

#--- end create git-revision.h ------------------------------------------------

#--- rpath related things -----------------------------------------------------
# use, i.e. don't skip the full RPATH for the build tree
set(CMAKE_SKIP_BUILD_RPATH FALSE)

# when building, don't use the install RPATH already
# (but later on when installing)
set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE)

set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_FULL_LIBDIR}")

# add the automatically determined parts of the RPATH
# which point to directories outside the build tree to the install RPATH
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

# the RPATH to be used when installing, but only if it's not a system directory
list(FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_FULL_LIBDIR}" isSystemDir)
if("${isSystemDir}" STREQUAL "-1")
    set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_FULL_LIBDIR}")
endif("${isSystemDir}" STREQUAL "-1")
if (UNIX AND NOT APPLE)
  set(rpath ${CMAKE_INSTALL_RPATH})
  string(APPEND rpath ";/usr/local/lib")
  set(CMAKE_INSTALL_RPATH "${rpath}")
elseif (APPLE)
  #--- on macOS the 3rd party libs typically come from Homebrew, which lives in
  #--- /opt/homebrew (Apple silicon) or /usr/local (Intel), or from MacPorts,
  #--- which lives in /opt/local on both architectures -----------------------
  set(rpath ${CMAKE_INSTALL_RPATH})
  if (EXISTS "/opt/homebrew/lib")
    string(APPEND rpath ";/opt/homebrew/lib")
  endif ()
  if (EXISTS "/usr/local/lib")
    string(APPEND rpath ";/usr/local/lib")
  endif ()
  if (EXISTS "/opt/local/lib")
    string(APPEND rpath ";/opt/local/lib")
  endif ()
  set(CMAKE_INSTALL_RPATH "${rpath}")
endif ()

#--- propagate to the sub-directories -----------------------------------------
add_subdirectory(src)

#--- testing ------------------------------------------------------------------
enable_testing()
add_subdirectory(tests)

#--- write summary of the installation
cmake_host_system_information(RESULT PROCESSOR QUERY PROCESSOR_DESCRIPTION)

message("")
message("|-----------------------------------------------------------------------|")
message("|                                                                       |")
message("|                            Summary                                    |")
message("|                                                                       |")
message("|-----------------------------------------------------------------------|")
message("")
message(" System:    ${CMAKE_HOST_SYSTEM_NAME} ${CMAKE_SYSTEM_PROCESSOR} - ${CMAKE_HOST_SYSTEM_VERSION}")
message(" Processor: ${PROCESSOR} (${CMAKE_SYSTEM_PROCESSOR})")
message(" ----------")
message("")
message(" musrfit Version: ${musrfit_VERSION}")
message(" ----------------")
message("")
message(" Build Type: ${CMAKE_BUILD_TYPE}")
message(" -----------")
message("")
message(" Requirements:")
message(" -------------")
message("")
message(" FFTW3   found in ${FFTW3_INCLUDE}, Version: ${FFTW_VERSION}")
message(" GSL     found in ${GSL_INCLUDE_DIRS}, Version: ${GSL_VERSION}")
message(" BOOST   found in ${Boost_INCLUDE_DIRS}, Version: ${Boost_VERSION}")
message(" LibXML2 found in ${LIBXML2_INCLUDE_DIR}, Version: ${LIBXML2_VERSION_STRING}")
message(" ROOT    found in ${ROOT_INCLUDE_DIRS}, Version: ${ROOT_VERSION}")
if (OpenMP_FOUND)
  if (OpenMP_CXX_VERSION)
    message(" OpenMP  found Version: ${OpenMP_CXX_VERSION}")
  else (OpenMP_CXX_VERSION)
    message(" OpenMP  found")
  endif (OpenMP_CXX_VERSION)
endif (OpenMP_FOUND)

if (nexus)
  message("")
  if (HAVE_HDF4)
    message(" HDF4    found in ${HDF4_INCLUDE_DIRS}, Version: ${HDF4_VERSION}")
  else (HAVE_HDF4)
    message(" HDF4    not present.")	  
  endif (HAVE_HDF4)	  
  message(" HDF5    found in ${HDF5_INCLUDE_DIRS}, Version: ${HDF5_VERSION}")
endif (nexus)

message("")
if (qt_based_tools)
  if (Qt6Core_FOUND)
    message(" Qt      found in  ${Qt6Core_INCLUDE_DIRS}, Version: ${Qt6Core_VERSION}")
  else (Qt6Core_FOUND)
    if (Qt5Core_FOUND)
      message(" Qt      found in  ${Qt5Core_INCLUDE_DIRS}, Version: ${Qt5Core_VERSION}")
    else (Qt5Core_FOUND)
      if (Qt4_FOUND)
        message(" Qt      found Version: ${QT_VERSION_MAJOR}.${QT_VERSION_MINOR}.${QT_VERSION_PATCH}")
      else (Qt4_FOUND)
        if (QT_FOUND)
          message(" Qt      found Version: ${QT_VERSION}")
        endif (QT_FOUND)
      endif (Qt4_FOUND)
    endif (Qt5Core_FOUND)
  endif (Qt6Core_FOUND)
endif (qt_based_tools)
message("")
message(" Features:")
message(" ---------")
message("")
message(" Supported muSR file formates:")
message("   MusrRoot                           : yes")
message("   ROOT (LEM)                         : yes")
message("   MUD (triumf)                       : yes")
message("   PSI-BIN                            : yes")
message("   PSI-MDU                            : yes")
message("   WKM (deprecated)                   : yes")
if (nexus)
  if (HAVE_HDF4)
    message("   NeXus                              : yes (HDF5 and HDF4)")
  else (HAVE_HDF4)
    message("   NeXus                              : yes (HDF5 only, -DHAVE_HDF4=1 adds HDF4)")
  endif (HAVE_HDF4)
else (nexus)
  message("   NeXus                              : no")
endif (nexus)

message("")
message(" External user-function libraries:")
if (ASlibs)
  message("   ASlibs                             : yes")
else (ASlibs)
  message("   ASlibs                             : no")
endif (ASlibs)
if (BMWlibs)
  message("   BMWlibs                            : yes")
else (BMWlibs)
  message("   BMWlibs                            : no")
endif (BMWlibs)
if (BNMRlibs)
  message("   BNMRlibs                           : yes")
else (BNMRlibs)
  message("   BNMRlibs                           : no")
endif (BNMRlibs)
if (DummyUserFcn)
  message("   PDummyUserFcn                      : yes")
endif (DummyUserFcn)

if (qt_based_tools)
if (Qt6Core_FOUND)
  message("")
  message(" Qt6 based tools:")
  message("   musredit, musrStep, musrWiz, mupp  : yes")
elseif (Qt5Core_FOUND)
  message("")
  message(" Qt5 based tools:")
  message("   musredit, musrStep, musrWiz, mupp  : yes")
elseif (Qt4_FOUND)
  message("")
  message(" Qt4 based tools (deprecated):")
  message("   musredit                           : yes")
else ()
  message("")
  message(" Qt3 based tools (outdated):")
  message("   musrgui                            : yes")
endif ()
if (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND AND NOT Qt4_FOUND AND NOT QT_FOUND)
  message("")
  message(" NO Qt based tools will be installed since Qt is not found or not installed on the system")
endif (NOT Qt6Core_FOUND AND NOT Qt5Core_FOUND AND NOT Qt4_FOUND AND NOT QT_FOUND)
else (qt_based_tools)
  message("")
  message(" Qt based tools (musredit, musrStep, musrWiz, mupp) have been disabled")
endif (qt_based_tools)
message("")
message(" Installation directories:")
message(" -------------------------")
message("")
message(" Programs                : ${CMAKE_INSTALL_PREFIX}/bin")
message(" XML configuration files : " $ENV{HOME} "/.musrfit")
message(" Documentation           : ${CMAKE_INSTALL_PREFIX}/share/doc/musrfit")
message("")
message("-------------------------------------------------------------------------")
message("")

#--- generate and install cmake package config files --------------------------
include(CMakePackageConfigHelpers)

configure_package_config_file(
  ${CMAKE_SOURCE_DIR}/cmake/musrfitConfig.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/musrfitConfig.cmake
  INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/musrfit
)

write_basic_package_version_file(
  ${CMAKE_CURRENT_BINARY_DIR}/musrfitConfigVersion.cmake
  VERSION ${PROJECT_VERSION}
  COMPATIBILITY AnyNewerVersion
)

install(
  EXPORT musrfitTargets
  FILE musrfitTargets.cmake
  NAMESPACE musrfit::
  DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/musrfit
)

install(
  FILES
    ${CMAKE_CURRENT_BINARY_DIR}/musrfitConfig.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/musrfitConfigVersion.cmake
  DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/musrfit
)

#--- cpack specific info ......................................................
file(TO_NATIVE_PATH ${PROJECT_SOURCE_DIR} PROJECT_SOURCE_DIR_NATIVE)
file(TO_NATIVE_PATH ${PROJECT_BINARY_DIR} PROJECT_BINARY_DIR_NATIVE)
string(REPLACE "\\" "\\\\" PROJECT_SOURCE_DIR_NATIVE_D ${PROJECT_SOURCE_DIR_NATIVE})
string(REPLACE "\\" "\\\\" PROJECT_BINARY_DIR_NATIVE_D ${PROJECT_BINARY_DIR_NATIVE})

configure_file(${CMAKE_SOURCE_DIR}/cmake/CPackOptions.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/CPackOptions.cmake @ONLY)
set (CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/CPackOptions.cmake")
#set (CPACK_GENERATOR TGZ) # not use ZIP on UNIX as problem with symlinks
#set (CPACK_SOURCE_GENERATOR TGZ) # not use ZIP on UNIX as problem with symlinks
#--- APPLE is UNIX as well, hence it needs to be excluded explicitly here,
#--- otherwise cpack would try to build an RPM on macOS ------------------------
if (UNIX AND NOT APPLE)
  set (CPACK_GENERATOR ${CPACK_GENERATOR};RPM)
endif ()
# Include of CPack must always be last
include(CPack)

#--- end ----------------------------------------------------------------------
