# This file contains a generic workaround to cause a list generated by
# a generator expression to be expanded when used as the COMMAND to
# add_custom_command() or add_custom_target().
# Using this workaround:
#  - include this file in CMakeLists.txt
#  - call expandable_command(<retvar> <command> [arg1] [arg2] ...)
#  - use the <retvar> from above as the COMMAND to add_custom_target()
#       or add_custom_command().
# Example to execute
#  echo a generated list
# code:
#  include(/path/to/expand_command.cmake)
#  expandable_command(cmdline echo $<TARGET_PROPERTY:echo,MSGLIST>)
#  add_custom_target(echo ALL COMMAND ${cmdline} VERBATIM)
#  set_property(TARGET echo PROPERTY MSGLIST a generated list)
if(NOT EXPAND_COMMAND_AS_SCRIPT)
    #==== This section is processed at configuration time when included
    if(COMMAND expandable_command)
        return()
    endif()

    set(EXPAND_COMMAND_SCRIPT "${CMAKE_CURRENT_LIST_FILE}")

    # Check if we are a case like VecGeom + VecCore where CUDA is
    # initialized by a sub-project (VecCore) but is used also in the
    # top project (VecGeom)
    get_directory_property(hasParent PARENT_DIRECTORY)
    if(hasParent)
      set(EXPAND_COMMAND_SCRIPT "${CMAKE_CURRENT_LIST_FILE}" PARENT_SCOPE)
    endif()

    function(expandable_command retvar)
        set(cmdline ${ARGN})
        string(REPLACE ";" "$<SEMICOLON>" cmdline "${cmdline}")
        set(${retvar} "${CMAKE_COMMAND}" "-D" "EXPAND_COMMAND_AS_SCRIPT=TRUE"
            "-D" "EXPAND_COMMAND=${cmdline}" "-P" "${EXPAND_COMMAND_SCRIPT}"
            PARENT_SCOPE)
    endfunction(expandable_command)

else()
    #==== This section is the command wrapper run at build time
    FOREACH(VAL ${EXPAND_COMMAND})
       STRING(REGEX REPLACE "^\"(.*)\"$" "\\1" VAL2 ${VAL})
       STRING(REGEX REPLACE "^,\"(.*)\"$" ",\\1" VAL3 ${VAL2})
       STRING(REGEX REPLACE "\",\"" "," VAL4 ${VAL3})
       LIST(APPEND real_cmd "${VAL4}")
    ENDFOREACH(VAL ${EXPAND_COMMAND})
    execute_process(COMMAND ${real_cmd}
                    ERROR_VARIABLE error
                    RESULT_VARIABLE result)
    set(stderr_type "")
    if(result)
        set(stderr_type FATAL_ERROR)
    endif()
    if(result OR error)
        message(${stderr_type} "${error}")
    endif()
endif()

