cmake_minimum_required(VERSION 3.16)
project(Parma VERSION 4.19 LANGUAGES CXX)  # the same version number as EXPACS and PARMA

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

option(PARMA_BUILD_TESTS "Build the regression tests" ON)
if(PARMA_BUILD_TESTS)
  enable_testing()
endif()

# The libraries are always static (BUILD_SHARED_LIBS is ignored): they export
# no symbols for a Windows DLL, and the shared tables are internal to them.
# They are compiled as position independent code, so that they can also be
# linked into a shared library (e.g. on Linux).
set(CMAKE_POSITION_INDEPENDENT_CODE ON)

# ---- core library (no Geant4 dependency) ----
add_library(parma_core STATIC
  core/src/Particle.cc
  core/src/ParmaData.cc
  core/src/ParmaModel.cc
  core/src/Environment.cc
  core/src/Log.cc
  core/src/PhysicsCondition.cc
  core/src/FluxGrid.cc
  core/src/AngularWeight.cc
  core/src/SamplingTable.cc
  core/src/EmissionSurface.cc
  core/src/Generator.cc)
add_library(Parma::parma_core ALIAS parma_core)
target_include_directories(parma_core PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/core/include>
  $<INSTALL_INTERFACE:include>)
# data directory used when neither an explicit path nor PARMA_DATA is given:
# the installed data, or the data of the source tree before the installation
include(GNUInstallDirs)
set(PARMA_INSTALL_DATADIR "${CMAKE_INSTALL_DATADIR}/Parma/data")
set(PARMA_INSTALL_CMAKEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/Parma")
target_compile_definitions(parma_core PRIVATE
  PARMA_DEFAULT_DATA_DIR="${CMAKE_INSTALL_PREFIX}/${PARMA_INSTALL_DATADIR}"
  PARMA_SOURCE_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data")
if(MSVC)
  target_compile_options(parma_core PRIVATE /W4)
  target_compile_definitions(parma_core PRIVATE _CRT_SECURE_NO_WARNINGS)
else()
  target_compile_options(parma_core PRIVATE -Wall -Wextra)
endif()

# ---- command line tool (successor of main-simple / main-generator) ----
add_executable(parma_cli tools/parma_cli.cpp)
target_link_libraries(parma_cli PRIVATE parma_core)
# the installed data relative to the installed executable, wherever the installation is
file(RELATIVE_PATH PARMA_CLI_RELATIVE_DATA_DIR "/prefix/${CMAKE_INSTALL_BINDIR}" "/prefix/${PARMA_INSTALL_DATADIR}")
target_compile_definitions(parma_cli PRIVATE PARMA_CLI_RELATIVE_DATA_DIR="${PARMA_CLI_RELATIVE_DATA_DIR}")

# ---- Geant4 interface and example (only if Geant4 is found) ----
option(PARMA_WITH_GEANT4 "Build the Geant4 interface if Geant4 is found" ON)
if(PARMA_WITH_GEANT4)
  find_package(Geant4 QUIET)
endif()
if(Geant4_FOUND)
  message(STATUS "Geant4 ${Geant4_VERSION} found: building parma_g4, ParmaBasic and ParmaCosmicray")
  add_library(parma_g4 STATIC
    geant4/src/ParmaPrimaryGenerator.cc
    geant4/src/ParmaPrimaryGeneratorMessenger.cc)
  add_library(Parma::parma_g4 ALIAS parma_g4)
  target_include_directories(parma_g4 PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/geant4/include>
    $<INSTALL_INTERFACE:include>)
  target_link_libraries(parma_g4 PUBLIC parma_core ${Geant4_LIBRARIES})
  add_subdirectory(examples/ParmaBasic)
  add_subdirectory(examples/Cosmicray)
else()
  message(STATUS "Geant4 not found: building the core and the command line tool only")
endif()

# ---- installation: libraries, headers, data, examples and the CMake package ----
#   find_package(Parma) then provides Parma::parma_core and, if built, Parma::parma_g4
include(CMakePackageConfigHelpers)
set(PARMA_TARGETS parma_core)
if(TARGET parma_g4)
  list(APPEND PARMA_TARGETS parma_g4)
  set(PARMA_WITH_G4 ON)
else()
  set(PARMA_WITH_G4 OFF)
endif()
install(TARGETS ${PARMA_TARGETS} parma_cli EXPORT ParmaTargets
  ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
  LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
  RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
install(DIRECTORY core/include/parma DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
if(PARMA_WITH_G4)
  install(DIRECTORY geant4/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
  install(DIRECTORY examples DESTINATION ${CMAKE_INSTALL_DATADIR}/Parma)
endif()
install(DIRECTORY data/ DESTINATION ${PARMA_INSTALL_DATADIR})
install(FILES README.md LICENSE DESTINATION ${CMAKE_INSTALL_DATADIR}/Parma)
install(EXPORT ParmaTargets NAMESPACE Parma:: DESTINATION ${PARMA_INSTALL_CMAKEDIR})
configure_package_config_file(cmake/ParmaConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/ParmaConfig.cmake
  INSTALL_DESTINATION ${PARMA_INSTALL_CMAKEDIR}
  PATH_VARS PARMA_INSTALL_DATADIR)
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/ParmaConfigVersion.cmake
  COMPATIBILITY SameMajorVersion)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/ParmaConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/ParmaConfigVersion.cmake
  DESTINATION ${PARMA_INSTALL_CMAKEDIR})

# ---- source package for the distribution:  cmake --build <build> --target dist ----
#      the distributed items are listed in cmake/MakeDist.cmake
add_custom_target(dist
  COMMAND ${CMAKE_COMMAND} -DOUTPUT=${CMAKE_CURRENT_BINARY_DIR}/parma-g4-${PROJECT_VERSION}.zip
          -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/MakeDist.cmake
  COMMENT "Creating parma-g4-${PROJECT_VERSION}.zip"
  VERBATIM)

# ---- tests ----
if(PARMA_BUILD_TESTS)
  add_executable(test_legacy tests/test_legacy.cc)
  target_link_libraries(test_legacy PRIVATE parma_core)
  add_test(NAME legacy_values
    COMMAND test_legacy ${CMAKE_CURRENT_SOURCE_DIR}/tests/reference/legacy_values.txt
                        ${CMAKE_CURRENT_SOURCE_DIR}/data)
  add_executable(test_environment tests/test_environment.cc)
  target_link_libraries(test_environment PRIVATE parma_core)
  add_test(NAME environment COMMAND test_environment ${CMAKE_CURRENT_SOURCE_DIR}/data)
  add_executable(test_generator tests/test_generator.cc)
  target_link_libraries(test_generator PRIVATE parma_core)
  add_test(NAME generator
    COMMAND test_generator ${CMAKE_CURRENT_SOURCE_DIR}/tests/reference
                           ${CMAKE_CURRENT_SOURCE_DIR}/data)
  # smoke tests of the command line tool
  add_test(NAME cli_flux
    COMMAND parma_cli flux -p neutron mu- -e 100 --cos -0.5 --data ${CMAKE_CURRENT_SOURCE_DIR}/data)
  add_test(NAME cli_generate
    COMMAND parma_cli generate -p neutron proton photon --energy 0.01 1e5 -n 2000 --bins 200 20
            -o ${CMAKE_CURRENT_BINARY_DIR} --data ${CMAKE_CURRENT_SOURCE_DIR}/data)

  # input checks of the core
  add_executable(test_validation tests/test_validation.cc)
  target_link_libraries(test_validation PRIVATE parma_core)
  add_test(NAME validation COMMAND test_validation ${CMAKE_CURRENT_SOURCE_DIR}/data)

  # input checks of the command line tool: <name> <expected message> <arguments separated by |>
  set(PARMA_CLI_REJECTED
    "duplicate_particle|given more than once|flux|-p|neutron|neutron|-e|1"
    "duplicate_all|given more than once|generate|-p|all|neutron|-n|10"
    "duplicate_id|given more than once|flux|-p|gamma|33|-e|1"
    "energy_nan|not a finite number: nan|flux|-p|neutron|-e|nan"
    "energy_range_inf|not a finite number: inf|generate|-p|neutron|--energy|1|inf"
    "wIndex_inf|not a finite number: inf|flux|-p|neutron|-e|1|--wIndex|inf"
    "wIndex_range|W-index -200 is out of the range|flux|-p|neutron|-e|1|--wIndex|-200"
    "cutoff_negative|cut-off rigidity .GV. -1 is out of the range|flux|-p|neutron|-e|1|--cutoff|-1"
    "depth_range|atmospheric depth .g/cm2. 2000 is out of the range|flux|-p|neutron|-e|1|--depth|2000"
    "geometry_range|local geometry parameter g 5 is out of the range|flux|-p|neutron|-e|1|--g|5"
    "latitude|latitude -100 deg is out of the range|flux|-p|neutron|-e|1|--location|-100|0|0"
    "longitude|longitude -181 deg is out of the range|flux|-p|neutron|-e|1|--location|0|-181|0"
    "altitude|altitude -1 km is out of the range|flux|-p|neutron|-e|1|--location|0|0|-1"
    "date_feb30|the date 1900/2/30 does not exist|flux|-p|neutron|-e|1|--date|1900|2|30"
    "date_not_leap|the date 2023/2/29 does not exist|flux|-p|neutron|-e|1|--date|2023|2|29"
    "date_century|the date 1900/2/29 does not exist|flux|-p|neutron|-e|1|--date|1900|2|29")
  foreach(spec ${PARMA_CLI_REJECTED})
    string(REPLACE "|" ";" spec "${spec}")
    list(POP_FRONT spec name expect)
    list(JOIN spec "|" args)
    add_test(NAME cli_rejects_${name}
      COMMAND ${CMAKE_COMMAND} "-DCOMMAND=$<TARGET_FILE:parma_cli>|${args}|--data|${CMAKE_CURRENT_SOURCE_DIR}/data"
              "-DEXPECT=${expect}" -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ExpectFailure.cmake)
  endforeach()
  # a negative W-index given directly, and a leap day
  add_test(NAME cli_negative_wIndex
    COMMAND parma_cli flux -p neutron -e 1 --wIndex -0.1 --data ${CMAKE_CURRENT_SOURCE_DIR}/data)
  set_tests_properties(cli_negative_wIndex PROPERTIES PASS_REGULAR_EXPRESSION "W-index= -0.1 ")
  add_test(NAME cli_leap_day
    COMMAND parma_cli flux -p neutron -e 1 --date 2024 2 29 --data ${CMAKE_CURRENT_SOURCE_DIR}/data)

  # input checks of the /parma/ commands with ParmaBasic (macros in tests/macros)
  if(TARGET ParmaBasic)
    set(dir ${CMAKE_CURRENT_BINARY_DIR}/tests)
    foreach(mac wIndex.mac rejected.mac rejected-mt.mac)
      configure_file(tests/macros/${mac} ${dir}/${mac} COPYONLY)
    endforeach()
    # a negative W-index given directly, then derived from the date again (multithreaded)
    add_test(NAME g4_wIndex COMMAND ParmaBasic wIndex.mac WORKING_DIRECTORY ${dir})
    set_tests_properties(g4_wIndex PROPERTIES
      PASS_REGULAR_EXPRESSION "W-index= -0.1,.*W-index= auto .date.*W-index= 17.2,"
      FAIL_REGULAR_EXPRESSION "Parma00[23]|Parma01[01]|COMMAND|\\*\\*\\* Fatal")
    # sequential: the refused command stops the macro before the tables are built
    add_test(NAME g4_rejects_serial COMMAND ParmaBasic rejected.mac WORKING_DIRECTORY ${dir})
    set_tests_properties(g4_rejects_serial PROPERTIES
      PASS_REGULAR_EXPRESSION "neutron is given more than once"
      FAIL_REGULAR_EXPRESSION "PARMA source")
    set_tests_properties(g4_rejects_serial PROPERTIES ENVIRONMENT "G4RUN_MANAGER_TYPE=Serial")
    set(g4_tests g4_wIndex g4_rejects_serial)
    # multithreaded: the run is stopped by a fatal G4Exception (abort) before the tables are built
    # (only with a multithreaded Geant4; otherwise the macro stops as in the sequential case)
    if(Geant4_multithreaded_FOUND)
      add_test(NAME g4_rejects_mt
        COMMAND ${CMAKE_COMMAND} "-DCOMMAND=$<TARGET_FILE:ParmaBasic>|rejected-mt.mac"
                "-DEXPECT=Parma011.*the date 1900/2/30 does not exist" "-DFORBID=PARMA source" -DANY_EXIT_CODE=ON
                -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ExpectFailure.cmake
        WORKING_DIRECTORY ${dir})
      list(APPEND g4_tests g4_rejects_mt)
    endif()
    if(WIN32)
      get_filename_component(G4_BIN_DIR "${Geant4_DIR}/../../../bin" ABSOLUTE)
      set_property(TEST ${g4_tests} APPEND PROPERTY
        ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:${G4_BIN_DIR}")
    endif()
  endif()
endif()
