#
# CMake script which is executed via cmake -P GenCppFile.cmake
# Generating a static cache initializer class and its source to statically initialize
# the GLOW shader cache. The variables are passed via the CMake cache.
#
# GLOW_CACHE_CPP_FILENAME: filename of the generated .cpp file.
# GLOW_CACHE_SHADER_FILENAMES: filenames of the shader files for which an entry should be generated.
#
# 
#  author: jens behley 
#

# needed to avoid calls with empty destination filename
if(GLOW_CACHE_CPP_FILENAME)
 
  file(LOCK ${GLOW_CACHE_CPP_FILENAME} RESULT_VARIABLE lock_status)
  # message(STATUS "lock_status = ${lock_status}")
  if(${lock_status} EQUAL "0")
  
    set(FILE_CONTENT "")
    
    # message(STATUS ">> GenCppFile: Writing shader source to '${GLOW_CACHE_CPP_FILENAME}'")
    # message(STATUS ">> GenCppFile: Shader files:  ${GLOW_CACHE_SHADER_FILENAMES}")
    
    get_filename_component(GLOW_CACHE_NAMESPACE ${GLOW_CACHE_CPP_FILENAME} NAME_WE)
    string(MAKE_C_IDENTIFIER ${GLOW_CACHE_NAMESPACE} GLOW_CACHE_NAMESPACE)
    # message(STATUS ">> namespace: '${GLOW_CACHE_NAMESPACE}'")
    
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "// GLOW_CACHE V10\n")
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "// This file is automatically generated. All changes will be lost when calling cmake.\n\n")
    
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "\#include <iostream>\n\#include <glow/GlShaderCache.h>\n\n")
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "namespace ${GLOW_CACHE_NAMESPACE} {\n")
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "class CacheInitalizer {\n public:\n   CacheInitalizer() {\n")
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"    "     glow::GlShaderCache& cache = glow::GlShaderCache::getInstance();\n")
    
    foreach(shader_file ${GLOW_CACHE_SHADER_FILENAMES})
      file(READ ${shader_file} content)
      
      # escape special characters for string variable. It might be neccessary to escape more then these?
      # Reminder: Quotes are important to avoid removal of ";"
      string(REPLACE "\n" "\\n" content "${content}")
      string(REPLACE "\"" "\\\"" content "${content}")
      
      string(CONCAT FILE_CONTENT  "${FILE_CONTENT}" "     cache.insertSource(\"${shader_file}\", \"${content}\");\n")
    endforeach()
    
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}" "   };\n};\n\n") 
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"   "static CacheInitalizer __init__;\n")
    string(CONCAT FILE_CONTENT "${FILE_CONTENT}"   "} // end namespace ${GLOW_CACHE_NAMESPACE}")
  
    
    file(LOCK ${GLOW_CACHE_CPP_FILENAME} RELEASE)
    file(WRITE ${GLOW_CACHE_CPP_FILENAME}  "${FILE_CONTENT}")

  endif()
  
endif()