set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")
include(AssetCache)

find_program(OGGENC NAMES oggenc NO_CMAKE_FIND_ROOT_PATH)
if(OGGENC AND DATADIR)
  file(GLOB_RECURSE FLAC_FILES RELATIVE ${DATADIR} ${DATADIR}/*.flac)
  message(STATUS "FlacToVorbis engaging... (using ${OGGENC})")
  foreach(file IN LISTS FLAC_FILES)
    message(STATUS ${file})
    string(REGEX REPLACE "^(.+)(\\.[^.]+)$" "\\1" filename ${file})
    GetFromAssetCache(${CACHE} ${DATADIR}/${file} "ogg-${BITRATE}-${SAMPLERATE}" CACHED HASH)
    if (CACHED)
      file(REMOVE ${DATADIR}/${file})
      configure_file(${CACHED} ${DATADIR}/${filename}.ogg COPYONLY)
      unset(CACHED)
    else()
      execute_process(COMMAND ${OGGENC} -Q -b ${BITRATE} --resample ${SAMPLERATE} ${file} -o ${filename}.ogg WORKING_DIRECTORY ${DATADIR} RESULT_VARIABLE OGGENC_RESULT)
      if(OGGENC_RESULT)
        message(WARNING "ERROR: ${OGGENC_RESULT}")
      else()
        file(REMOVE ${DATADIR}/${file})
        AddToAssetCache(${CACHE} ${HASH} "ogg-${BITRATE}-${SAMPLERATE}" "${DATADIR}/${filename}.ogg")
      endif()
    endif()
  endforeach(file)
else(OGGENC AND DATADIR)
  if(NOT OGGENC)
    message(WARNING "FlacToVorbis: can't find oggenc!")
  else()
    message(WARNING "FlacToVorbis: no DATADIR specified!")
  endif()
endif(OGGENC AND DATADIR)