#autogenerated struct files
#
#this cmake script creates rules for generated files
#
#the gamedata format is defined in the convert script,
#and it can dynamically be exported to C code.

#look for the python3.3 executable
find_file(PYTHON3 python3 HINTS /usr/bin/python3.3 /usr/bin/python3.4)

if(${PYTHON3} STREQUAL "PYTHON3-NOTFOUND")
	message(FATAL "python >= 3.3 not found.")
else()
	message(STATUS "Found python executable: ${PYTHON3}")
endif()


#the convert script invocation
set(CONVERT_CALL ${PYTHON3} convert structs)

#ask the convert script which source files it can generate
execute_process(COMMAND
	${CONVERT_CALL} "--list-files"
	WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}
	OUTPUT_VARIABLE FILES_TO_GENERATE
	RESULT_VARIABLE GEN_LIST_RESULT
)

#when python returned != 1:
if(${GEN_LIST_RESULT})
	message(FATAL_ERROR "failed creating filelist by convert script")
endif()

#where the generated files will be put: this folder.
set(DESTINATION_FOLDER "${CMAKE_CURRENT_SOURCE_DIR}/")

#create conversion command for each file to generate
set(FILE_RULES "")
set(COMPILE_FILES "")

foreach(FILE_NAME ${FILES_TO_GENERATE})
	#this file will be generated by the command
	set(GEN_FILE "${DESTINATION_FOLDER}${FILE_NAME}")

	#regeneration dependencies.
	#actually depends on many more: TODO
	set(GEN_FILE_DEPENDENCIES "${PROJECT_SOURCE_DIR}/convert/dataformat.py")

	#add command that cmake will use if file needs to be generated
	add_custom_command(
		OUTPUT ${GEN_FILE}
		COMMAND ${CONVERT_CALL} -o "${DESTINATION_FOLDER}" "${FILE_NAME}"
		WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
		DEPENDS ${GEN_FILE_DEPENDENCIES}
		COMMENT "generating ${FILE_NAME}"
	)
	message("creating generation rule for '${FILE_NAME}'")
	list(APPEND FILE_RULES "${GEN_FILE}")

	if(NOT "${GEN_FILE}" MATCHES ".h$")
		list(APPEND COMPILE_FILES "${GEN_FILE}")
	endif()
endforeach()

#static library for the generated files
add_library(gamedata STATIC ${FILE_RULES})

#target for explicit generation of files
add_custom_target(filegeneration ALL DEPENDS ${FILE_RULES})
