#################################################
#                                               #
#  Auxiliary macros for KMyMoney                #
#                                               #
#################################################

include( TDEMacros )


#################################################
#####
##### kmm_install_includes
#####
##### The macro is used to determine the headers that are installed,
##### while the symlinks in the binary include directory are created.
#####
##### Syntax:
#####   kmm_install_includes(
#####     [FILES] include_name [include_name]
#####     [DESTINATION subdir]
#####   )

macro( kmm_install_includes )

  unset( _files )
  unset( _dest )
  set( _var _files )

  foreach( _arg ${ARGN} )

    # found directive "FILES"
    if( "+${_arg}" STREQUAL "+FILES" )
      unset( _files )
      set( _var _files )
      set( _directive 1 )
    endif( )

    # found directive "DESTINATION"
    if( "+${_arg}" STREQUAL "+DESTINATION" )
      unset( _dest )
      set( _var _dest )
      set( _directive 1 )
    endif( )

    # collect data
    if( _directive )
      unset( _directive )
    elseif( _var )
      list( APPEND ${_var} ${_arg} )
    endif( )

  endforeach( )

  # determine destination directory
  if( NOT IS_ABSOLUTE "${_dest}" )
    set( _dest "${INCLUDE_INSTALL_DIR}/${_dest}" )
  endif()
  file( RELATIVE_PATH _dest_sub "${INCLUDE_INSTALL_DIR}" "${_dest}" )
  file( MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/include/${_dest_sub}" )

  # process files
  foreach( _file IN LISTS _files )
    if( NOT TARGET kmm-includes )
      add_custom_target( kmm-includes
        WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
        COMMENT "Prepare includes..." )
    endif()

    get_filename_component( _source_name "${_file}" NAME )
    get_filename_component( _source_file "${_file}" ABSOLUTE )
    file( RELATIVE_PATH _target_name "${CMAKE_SOURCE_DIR}" "${_source_file}" )
    string( REPLACE "/" "+" _target_name "${_target_name}" )

    file( RELATIVE_PATH _link_source "${CMAKE_BINARY_DIR}/include/${_dest_sub}" ${_source_file} )
    file( RELATIVE_PATH _link_dest "${INCLUDE_INSTALL_DIR}" "${_dest}/${_source_name}" )

    add_custom_command(
      OUTPUT ${CMAKE_BINARY_DIR}/include/${_link_dest}
      COMMAND
        ${CMAKE_COMMAND} -E create_symlink
        ${_link_source} ${CMAKE_BINARY_DIR}/include/${_link_dest}
      COMMENT "Include file ${_link_dest}"
      DEPENDS ${_source_file}
    )
    add_custom_target( ${_target_name}
      DEPENDS ${CMAKE_BINARY_DIR}/include/${_link_dest}
    )
    add_dependencies( kmm-includes ${_target_name} )

    install( FILES ${_file} DESTINATION ${_dest} )
  endforeach( _file )

endmacro( kmm_install_includes )
