--
-- _cmake.lua
-- Define the CMake action(s).
-- Copyright (c) 2015 Miodrag Milanovic
--

function premake.cmake.workspace(sln)
	_p('# CMakeLists autogenerated by GENie')
	_p('# https://github.com/bkaradzic/GENie')
	_p('cmake_minimum_required(VERSION %s)', premake.cmake.cmake_minimum_version)
	if os.is("windows") then
		-- Add support for CMP0091, see https://cmake.org/cmake/help/latest/policy/CMP0091.html
		_p('cmake_policy(SET CMP0091 NEW)')
	end
	_p('project(%s)', sln.name)
	_p('set(CMAKE_SUPPRESS_REGENERATION true)')
	_p('# Strip default /EHsc — each project manages exception handling explicitly')
	_p('if(MSVC)')
	_p(1, 'string(REPLACE "/EHsc" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")')
	_p('endif()')
	_p('get_property(_isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)')
	_p('if(NOT _isMultiConfig AND NOT CMAKE_BUILD_TYPE)')
	_p(1, 'message(FATAL_ERROR')
	_p(2, '"CMAKE_BUILD_TYPE is not set."')
	_p(2, '" Single-config generators require an explicit build type."')
	_p(2, '" Use: cmake --preset <config> or -DCMAKE_BUILD_TYPE=<config>"')
	_p(1, ')')
	_p('endif()')
	_p('set_property(GLOBAL PROPERTY USE_FOLDERS ON)')
	_p('set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER "[GENie-Generated-CMake]")')
	_p('add_subdirectory(cmake/%s)', sln.name)
	if sln.startproject then
		_p('set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT %s)', premake.esc(sln.startproject))
	end

end

function premake.cmake.gateway(sln)
	_p('# Auto-generated by GENie')
	_p('# https://github.com/bkaradzic/GENie')
	for i,prj in ipairs(sln.projects) do
		_p('include(%s.cmake)', premake.esc(prj.name))
	end
end

function premake.cmake.presets(sln)
	_p('{')
	_p('  "version": 3,')
	_p('  "configurePresets": [')
	_p('    {')
	_p('      "name": "default",')
	_p('      "binaryDir": "${sourceDir}/build"')
	_p('    },')
	for i, cfgname in ipairs(sln.configurations) do
		local comma = i < #sln.configurations and ',' or ''
		_p('    {')
		_p('      "name": "%s",', cfgname:lower())
		_p('      "binaryDir": "${sourceDir}/build",')
		_p('      "cacheVariables": {')
		_p('        "CMAKE_BUILD_TYPE": "%s"', cfgname)
		_p('      }')
		_p('    }%s', comma)
	end
	_p('  ]')
	_p('}')
end
