# Simple, recursive cfg parser to extract cfg paths, linker script paths, and
# link directories. CMake uses this information to set up in-tree build
# dependencies and link directories. This is not a proper tokenizer, so -T and
# -L flags must be on one line and contain no whitespace or quoted paths.
function(read_config_deps cfg_file cfg_list_var ld_list_var link_dir_list_var)
  if(${cfg_file} IN_LIST ${cfg_list_var})
    return()
  endif()
  list(APPEND ${cfg_list_var} ${cfg_file})
  get_filename_component(cur_dir ${cfg_file} DIRECTORY)
  file(STRINGS ${cfg_file} config_file_lines)
  foreach(line ${config_file_lines})
    if(line MATCHES "\@([^ \t\r\n]+)")
      # Handle config file include
      set(match ${CMAKE_MATCH_1})
      if(NOT IS_ABSOLUTE ${match})
        string(PREPEND match "${cur_dir}/")
      endif()
      get_filename_component(match ${match} ABSOLUTE)
      if(EXISTS ${match})
        read_config_deps(${match} ${cfg_list_var} ${ld_list_var} ${link_dir_list_var})
      endif()
    else()
      # Extract library paths and linker scripts
      function(_extract_flags flag list_var)
        string(REGEX MATCHALL "${flag}[ \t]*[^ \t]+" matches ${line})
        foreach(match ${matches})
          string(REGEX REPLACE "${flag}[ \t]*([^ \t]+)" "\\1" match ${match})
          string(REPLACE "<CFGDIR>" "${cur_dir}" match ${match})
          get_filename_component(match ${match} ABSOLUTE)
          if(EXISTS ${match})
            list(APPEND ${list_var} ${match})
          endif()
        endforeach()
        set(${list_var} ${${list_var}} PARENT_SCOPE)
      endfunction()
      _extract_flags(-T ${ld_list_var})
      _extract_flags(-L ${link_dir_list_var})
    endif()
  endforeach()
  set(${cfg_list_var} ${${cfg_list_var}} PARENT_SCOPE)
  set(${ld_list_var} ${${ld_list_var}} PARENT_SCOPE)
  set(${link_dir_list_var} ${${link_dir_list_var}} PARENT_SCOPE)
endfunction()
