#
#  Singe 2
#  Copyright (C) 2006-2024 Scott Duensing <scott@kangaroopunch.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public Licens
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#


cmake_minimum_required(VERSION 3.22)
project(singe2 VERSION 2.20 LANGUAGES C)

set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)

# The copyright end year tracks the build date so nothing has to be hand edited.
string(TIMESTAMP SINGE_COPYRIGHT_END_YEAR "%Y")


if(NOT DEFINED KANGAROO_OS)
	set(KANGAROO_OS linux)
endif()
if(NOT DEFINED KANGAROO_ARCH)
	set(KANGAROO_ARCH x86_64)
endif()

# Where build-all.sh installed the third party libraries for this platform.
set(BUILD_DIR ${CMAKE_SOURCE_DIR}/.builddir/${KANGAROO_OS}/${KANGAROO_ARCH})
set(GENERATED_DIR ${CMAKE_BINARY_DIR}/generated)
file(MAKE_DIRECTORY ${GENERATED_DIR})


# ===== Host tools needed to generate embedded resources =====

find_program(IMAGEMAGICK NAMES magick convert)
if(NOT IMAGEMAGICK)
	message(FATAL_ERROR "ImageMagick (magick or convert) is required to render the embedded images.")
endif()
find_program(FFMPEG_TOOL NAMES ffmpeg)
if(NOT FFMPEG_TOOL)
	message(FATAL_ERROR "ffmpeg is required to build the menu background video.")
endif()
find_program(LUA_TOOL NAMES lua5.4 lua)
if(NOT LUA_TOOL)
	message(FATAL_ERROR "A Lua interpreter is required to generate the LuaSec option table.")
endif()
find_program(ASCIIDOCTOR_PDF NAMES asciidoctor-pdf)
if(NOT ASCIIDOCTOR_PDF)
	message(FATAL_ERROR "asciidoctor-pdf is required to build the embedded manual (gem install asciidoctor-pdf rouge).")
endif()
find_program(ASCIIDOCTOR NAMES asciidoctor)


# ===== Generated sources =====

# Version header and Windows resources come from the project() line above.
configure_file(src/version.h.in ${GENERATED_DIR}/version.h @ONLY)
configure_file(src/singe.rc.in ${GENERATED_DIR}/singe.rc @ONLY)

# LuaSec needs its headers reachable as <luasocket/...>.
file(GLOB LUASOCKET_HEADERS thirdparty/luasocket/src/*.h)
file(COPY ${LUASOCKET_HEADERS} DESTINATION ${GENERATED_DIR}/include/luasocket)

# LuaSec option table generated from the OpenSSL headers that were built.
add_custom_command(
	OUTPUT ${GENERATED_DIR}/luasec_options.c
	COMMAND ${CMAKE_COMMAND} -DOUTPUT=${GENERATED_DIR}/luasec_options.c -DCOMMAND=${LUA_TOOL} "-DARGS=${CMAKE_SOURCE_DIR}/thirdparty/luasec/src/options.lua;-g;${BUILD_DIR}/include/openssl/ssl.h" -P ${CMAKE_SOURCE_DIR}/cmake/runToFile.cmake
	DEPENDS thirdparty/luasec/src/options.lua ${BUILD_DIR}/include/openssl/ssl.h cmake/runToFile.cmake
	COMMENT "Generating LuaSec options"
	VERBATIM
)

# Embeds a file as a C array.  The symbol name is derived from the file name, as xxd does.
set(EMBEDDED_HEADERS)
function(singeEmbed input output prefix)
	get_filename_component(name ${input} NAME)
	string(MAKE_C_IDENTIFIER "${prefix}${name}" symbol)
	get_filename_component(guardName ${output} NAME)
	string(MAKE_C_IDENTIFIER "${guardName}" guard)
	string(TOUPPER "${guard}" guard)
	add_custom_command(
		OUTPUT ${output}
		COMMAND ${CMAKE_COMMAND} -DINPUT=${input} -DOUTPUT=${output} -DGUARD=${guard} -DSYMBOL=${symbol} -DCOPYRIGHT_END_YEAR=${SINGE_COPYRIGHT_END_YEAR} -P ${CMAKE_SOURCE_DIR}/cmake/embed.cmake
		DEPENDS ${input} cmake/embed.cmake
		COMMENT "Embedding ${name}"
		VERBATIM
	)
	set(EMBEDDED_HEADERS ${EMBEDDED_HEADERS} ${output} PARENT_SCOPE)
endfunction()

# Renders a layered image to a flattened PNG and embeds it.
function(singeEmbedImage name)
	add_custom_command(
		OUTPUT ${GENERATED_DIR}/${name}.png
		COMMAND ${IMAGEMAGICK} ${CMAKE_SOURCE_DIR}/assets/${name}.xcf -background "rgba(0,0,0,0)" -flatten ${GENERATED_DIR}/${name}.png
		DEPENDS assets/${name}.xcf
		COMMENT "Rendering ${name}.png"
		VERBATIM
	)
	singeEmbed(${GENERATED_DIR}/${name}.png ${GENERATED_DIR}/${name}.h "")
	set(EMBEDDED_HEADERS ${EMBEDDED_HEADERS} PARENT_SCOPE)
endfunction()

# Embeds a Lua module from the third party tree.
function(singeEmbedLua path prefix)
	get_filename_component(name ${path} NAME_WE)
	singeEmbed(${CMAKE_SOURCE_DIR}/${path} ${GENERATED_DIR}/${prefix}${name}_lua.h "${prefix}")
	set(EMBEDDED_HEADERS ${EMBEDDED_HEADERS} PARENT_SCOPE)
endfunction()

# Images
singeEmbedImage(font)
singeEmbedImage(icon)
singeEmbedImage(kangarooPunchLogo)
singeEmbedImage(singeLogo)
singeEmbedImage(laserDisc)
singeEmbedImage(magnifyingGlass)
singeEmbedImage(indexing)

# Windows icon for the resource file.
add_custom_command(
	OUTPUT ${GENERATED_DIR}/icon.ico
	COMMAND ${IMAGEMAGICK} ${GENERATED_DIR}/icon.png -define icon:auto-resize=64,48,32,16 ${GENERATED_DIR}/icon.ico
	DEPENDS ${GENERATED_DIR}/icon.png
	COMMENT "Rendering icon.ico"
	VERBATIM
)

# Support files extracted at first run.
singeEmbed(${CMAKE_SOURCE_DIR}/assets/Framework.singe ${GENERATED_DIR}/Framework_singe.h "")
singeEmbed(${CMAKE_SOURCE_DIR}/assets/controls.cfg ${GENERATED_DIR}/controls_cfg.h "")
singeEmbed(${CMAKE_SOURCE_DIR}/assets/Menu.singe ${GENERATED_DIR}/Menu_singe.h "")
singeEmbed(${CMAKE_SOURCE_DIR}/assets/FreeSansBold.ttf ${GENERATED_DIR}/FreeSansBold_ttf.h "")

# Menu background video:  two clips cropped to 4:3, scaled to 720x480, and joined.
file(WRITE ${GENERATED_DIR}/menuBackground.txt "file ${GENERATED_DIR}/menuBackground1.mkv\nfile ${GENERATED_DIR}/menuBackground2.mkv\n")
add_custom_command(
	OUTPUT ${GENERATED_DIR}/menuBackground.mkv
	COMMAND ${FFMPEG_TOOL} -y -loglevel error -i "${CMAKE_SOURCE_DIR}/assets/Singe Engine Intro.mpg" -filter:v "crop=ih/3*4:ih,scale=720:480" -c:v libx264 -c:a aac -f matroska ${GENERATED_DIR}/menuBackground1.mkv
	COMMAND ${FFMPEG_TOOL} -y -loglevel error -i ${CMAKE_SOURCE_DIR}/assets/180503_01_PurpleGrid.mp4 -filter:v "crop=ih/3*4:ih,scale=720:480" -c:v libx264 -c:a aac -f matroska ${GENERATED_DIR}/menuBackground2.mkv
	COMMAND ${FFMPEG_TOOL} -y -loglevel error -f concat -safe 0 -i ${GENERATED_DIR}/menuBackground.txt -c copy ${GENERATED_DIR}/menuBackground.mkv
	DEPENDS "assets/Singe Engine Intro.mpg" assets/180503_01_PurpleGrid.mp4
	COMMENT "Building menuBackground.mkv"
	VERBATIM
)
singeEmbed(${GENERATED_DIR}/menuBackground.mkv ${GENERATED_DIR}/menuBackground_mkv.h "")

# Manual, rendered from the AsciiDoc source and shipped inside the binary.
add_custom_command(
	OUTPUT ${GENERATED_DIR}/Manual.pdf
	COMMAND ${ASCIIDOCTOR_PDF} -a revnumber=${PROJECT_VERSION} ${CMAKE_SOURCE_DIR}/docs/Manual.adoc -o ${GENERATED_DIR}/Manual.pdf
	DEPENDS docs/Manual.adoc
	COMMENT "Rendering Manual.pdf"
	VERBATIM
)
singeEmbed(${GENERATED_DIR}/Manual.pdf ${GENERATED_DIR}/Manual_pdf.h "")

# Lua libraries
singeEmbedLua(thirdparty/luasocket/src/ftp.lua "")
singeEmbedLua(thirdparty/luasocket/src/headers.lua "")
singeEmbedLua(thirdparty/luasocket/src/http.lua "")
singeEmbedLua(thirdparty/luasocket/src/ltn12.lua "")
singeEmbedLua(thirdparty/luasocket/src/mbox.lua "")
singeEmbedLua(thirdparty/luasocket/src/mime.lua "")
singeEmbedLua(thirdparty/luasocket/src/smtp.lua "")
singeEmbedLua(thirdparty/luasocket/src/socket.lua "")
singeEmbedLua(thirdparty/luasocket/src/tp.lua "")
singeEmbedLua(thirdparty/luasocket/src/url.lua "")
singeEmbedLua(thirdparty/luasec/src/https.lua "")
singeEmbedLua(thirdparty/luasec/src/ssl.lua "")
singeEmbedLua(thirdparty/librs232/bindings/lua/rs232.lua "")
singeEmbedLua(thirdparty/copas/src/copas.lua "")
singeEmbedLua(thirdparty/copas/src/copas/ftp.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/http.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/smtp.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/lock.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/queue.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/semaphore.lua "copas_")
singeEmbedLua(thirdparty/copas/src/copas/timer.lua "copas_")
singeEmbedLua(thirdparty/binaryheap.lua/src/binaryheap.lua "")
singeEmbedLua(thirdparty/timerwheel.lua/src/timerwheel/timerwheel.lua "")
singeEmbedLua(thirdparty/json.lua/json.lua "")

# Optional HTML manual for browsing:  cmake --build . --target docs
if(ASCIIDOCTOR)
	add_custom_target(docs
		COMMAND ${ASCIIDOCTOR} -a revnumber=${PROJECT_VERSION} ${CMAKE_SOURCE_DIR}/docs/Manual.adoc -o ${CMAKE_BINARY_DIR}/Manual.html
		DEPENDS ${GENERATED_DIR}/Manual.pdf
		COMMENT "Rendering Manual.html"
		VERBATIM
	)
endif()


# ===== Sources =====

set(SINGE_SOURCE
	src/common.h
	src/embedded.h
	src/frameFile.c
	src/frameFile.h
	src/main.c
	src/main.h
	src/singe.c
	src/singe.h
	src/stddclmr.h
	src/util.c
	src/util.h
	src/videoPlayer.c
	src/videoPlayer.h
)

set(ARG_PARSER_SOURCE
	thirdparty/arg_parser/carg_parser.c
	thirdparty/arg_parser/carg_parser.h
)

file(GLOB LUA_SOURCE thirdparty/lua/src/*.c thirdparty/lua/src/*.h)
list(FILTER LUA_SOURCE EXCLUDE REGEX "/(lua|luac|onelua)\\.c$")

set(LUA_FILESYSTEM_SOURCE
	thirdparty/luafilesystem/src/lfs.c
	thirdparty/luafilesystem/src/lfs.h
)

set(LUA_SOCKET_SOURCE
	thirdparty/luasocket/src/auxiliar.c
	thirdparty/luasocket/src/auxiliar.h
	thirdparty/luasocket/src/buffer.c
	thirdparty/luasocket/src/buffer.h
	thirdparty/luasocket/src/compat.c
	thirdparty/luasocket/src/compat.h
	thirdparty/luasocket/src/except.c
	thirdparty/luasocket/src/except.h
	thirdparty/luasocket/src/inet.c
	thirdparty/luasocket/src/inet.h
	thirdparty/luasocket/src/io.c
	thirdparty/luasocket/src/io.h
	thirdparty/luasocket/src/luasocket.c
	thirdparty/luasocket/src/luasocket.h
	thirdparty/luasocket/src/mime.c
	thirdparty/luasocket/src/mime.h
	thirdparty/luasocket/src/options.c
	thirdparty/luasocket/src/options.h
	thirdparty/luasocket/src/select.c
	thirdparty/luasocket/src/select.h
	thirdparty/luasocket/src/socket.h
	thirdparty/luasocket/src/tcp.c
	thirdparty/luasocket/src/tcp.h
	thirdparty/luasocket/src/timeout.c
	thirdparty/luasocket/src/timeout.h
	thirdparty/luasocket/src/udp.c
	thirdparty/luasocket/src/udp.h
)
if(WIN32)
	list(APPEND LUA_SOCKET_SOURCE
		thirdparty/luasocket/src/wsocket.c
		thirdparty/luasocket/src/wsocket.h
	)
else()
	list(APPEND LUA_SOCKET_SOURCE
		thirdparty/luasocket/src/serial.c
		thirdparty/luasocket/src/unix.c
		thirdparty/luasocket/src/unix.h
		thirdparty/luasocket/src/unixdgram.c
		thirdparty/luasocket/src/unixdgram.h
		thirdparty/luasocket/src/unixstream.c
		thirdparty/luasocket/src/unixstream.h
		thirdparty/luasocket/src/usocket.c
		thirdparty/luasocket/src/usocket.h
	)
endif()

set(LUASEC_SOURCE
	${GENERATED_DIR}/luasec_options.c
	thirdparty/luasec/src/compat.h
	thirdparty/luasec/src/config.c
	thirdparty/luasec/src/context.c
	thirdparty/luasec/src/context.h
	thirdparty/luasec/src/ec.c
	thirdparty/luasec/src/ec.h
	thirdparty/luasec/src/options.h
	thirdparty/luasec/src/ssl.c
	thirdparty/luasec/src/ssl.h
	thirdparty/luasec/src/x509.c
	thirdparty/luasec/src/x509.h
)

set(LUA_RS232_SOURCE
	thirdparty/librs232/bindings/lua/luars232.c
	thirdparty/librs232/src/rs232.c
)
if(WIN32)
	list(APPEND LUA_RS232_SOURCE thirdparty/librs232/src/rs232_windows.c)
else()
	list(APPEND LUA_RS232_SOURCE thirdparty/librs232/src/rs232_posix.c)
endif()

set(UTHASH_SOURCE
	thirdparty/uthash/src/uthash.h
	thirdparty/uthash/src/utlist.h
)

set(MANYMOUSE_SOURCE
	thirdparty/manymouse/linux_evdev.c
	thirdparty/manymouse/macosx_hidmanager.c
	thirdparty/manymouse/macosx_hidutilities.c
	thirdparty/manymouse/manymouse.c
	thirdparty/manymouse/manymouse.h
	thirdparty/manymouse/windows_wminput.c
	thirdparty/manymouse/x11_xinput2.c
)

set(SDL2_GFX_SOURCE
	thirdparty/SDL2_gfx/SDL2_rotozoom.h
	thirdparty/SDL2_gfx/SDL2_rotozoom.c
)


# ===== Target =====

add_executable(${CMAKE_PROJECT_NAME}
	${SINGE_SOURCE}
	${EMBEDDED_HEADERS}
	${GENERATED_DIR}/version.h
	${ARG_PARSER_SOURCE}
	${LUA_SOURCE}
	${LUA_FILESYSTEM_SOURCE}
	${LUA_SOCKET_SOURCE}
	${LUASEC_SOURCE}
	${LUA_RS232_SOURCE}
	${UTHASH_SOURCE}
	${MANYMOUSE_SOURCE}
	${SDL2_GFX_SOURCE}
)
if(WIN32)
	enable_language(RC)
	target_sources(${CMAKE_PROJECT_NAME} PRIVATE ${GENERATED_DIR}/singe.rc ${GENERATED_DIR}/icon.ico)
endif()

# Output name matches the release artifact:  Singe-v2.20-Linux-x86_64
string(SUBSTRING ${KANGAROO_OS} 0 1 osInitial)
string(SUBSTRING ${KANGAROO_OS} 1 -1 osRest)
string(TOUPPER ${osInitial} osInitial)
set_target_properties(${CMAKE_PROJECT_NAME} PROPERTIES OUTPUT_NAME "Singe-v${PROJECT_VERSION}-${osInitial}${osRest}-${KANGAROO_ARCH}")

# Warnings apply to our code only; the vendored libraries are not ours to fix.
set_source_files_properties(${SINGE_SOURCE} PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra")

target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
	RS232_STATIC
	FFMS_STATIC
)
if(WIN32)
	# _WIN32_WINNT=0x0600 sets the minimum compatible version of Windows to Vista.
	# The function inet_pton() does not exist before then.
	target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
		main=SDL_main
		_WIN32_WINNT=0x0600
	)
endif()

target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE
	-Wno-deprecated-declarations
)

target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
	${CMAKE_BINARY_DIR}
	${GENERATED_DIR}/include
	${BUILD_DIR}
	${BUILD_DIR}/include
	${BUILD_DIR}/include/SDL2
	thirdparty/lua/src
	thirdparty/luasec/src
	thirdparty/librs232/include
)

target_link_directories(${CMAKE_PROJECT_NAME} PRIVATE
	${BUILD_DIR}/lib
)


# ===== Libraries =====

# Platform specific system libraries.
if(KANGAROO_OS STREQUAL "linux")
	# ffmpeg's vdpau hardware context is always compiled in on X11 hosts.
	set(SYSTEM_LIBS -lX11 -lvdpau)
elseif(KANGAROO_OS STREQUAL "pi")
	set(SYSTEM_LIBS)
elseif(KANGAROO_OS STREQUAL "macos")
	set(SYSTEM_LIBS
		-Wl,-framework,CoreVideo
		-Wl,-framework,Cocoa
		-Wl,-framework,IOKit
		-Wl,-framework,ForceFeedback
		-Wl,-framework,Carbon
		-Wl,-framework,CoreAudio
		-Wl,-framework,AudioToolbox
		-Wl,-framework,AVFoundation
		-Wl,-framework,Foundation
		-Wl,-weak_framework,GameController
		-Wl,-weak_framework,Metal
		-Wl,-weak_framework,QuartzCore
		-Wl,-weak_framework,CoreHaptics
		-liconv
		-lc++
		${OSXCROSS_TARGET_DIR}/darwin/libclang_rt.osx.a
	)
	if(NOT DEFINED OSXCROSS_TARGET_DIR)
		message(FATAL_ERROR "OSXCROSS_TARGET_DIR must be set for macOS builds.")
	endif()
elseif(KANGAROO_OS STREQUAL "windows")
	set(SYSTEM_LIBS
		-mwindows
		-static
		-lmingw32
		-latomic
		-lole32
		-luser32
		-lkernel32
		-lgdi32
		-lwinmm
		-limm32
		-loleaut32
		-lversion
		-luuid
		-ladvapi32
		-lsetupapi
		-lshell32
		-ldinput8
		-lws2_32
		-lbcrypt
		-lssp
		-lcrypt32
	)
else()
	message(FATAL_ERROR "Unknown KANGAROO_OS:  ${KANGAROO_OS}")
endif()

# Static third party libraries built by build-all.sh.
set(STATIC_LIBS
	${BUILD_DIR}/lib/libarchive.a
	${BUILD_DIR}/lib/libavcodec.a
	${BUILD_DIR}/lib/libavdevice.a
	${BUILD_DIR}/lib/libavfilter.a
	${BUILD_DIR}/lib/libavformat.a
	${BUILD_DIR}/lib/libavutil.a
	${BUILD_DIR}/lib/libbz2_static.a
	${BUILD_DIR}/lib/libffms2.a
	${BUILD_DIR}/lib/libfreetype.a
	${BUILD_DIR}/lib/liblzma.a
	${BUILD_DIR}/lib/libopus.a
	${BUILD_DIR}/lib/libopusfile.a
	${BUILD_DIR}/lib/libogg.a
	${BUILD_DIR}/lib/libpostproc.a
	${BUILD_DIR}/lib/libSDL2.a
	${BUILD_DIR}/lib/libSDL2_image.a
	${BUILD_DIR}/lib/libSDL2main.a
	${BUILD_DIR}/lib/libSDL2_mixer.a
	${BUILD_DIR}/lib/libSDL2_ttf.a
	${BUILD_DIR}/lib/libswresample.a
	${BUILD_DIR}/lib/libswscale.a
	${BUILD_DIR}/lib/libwavpack.a
	${BUILD_DIR}/lib/libwebp.a
	${BUILD_DIR}/lib/libwebpdemux.a
	${BUILD_DIR}/lib/libxmp.a
	${BUILD_DIR}/lib/libz.a
	${BUILD_DIR}/lib/libzstd.a
	${BUILD_DIR}/lib/libcrypto.a
	${BUILD_DIR}/lib/libssl.a
)
if(NOT KANGAROO_OS STREQUAL "macos")
	list(APPEND STATIC_LIBS
		${BUILD_DIR}/lib/libjpeg.a
		${BUILD_DIR}/lib/libpng.a
		-lstdc++
	)
endif()

# System libraries follow the static ones so their symbols resolve for everything above.
# Apple's linker has no --start-group, so the list is repeated there instead.
if(KANGAROO_OS STREQUAL "macos")
	target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE ${STATIC_LIBS} ${STATIC_LIBS} ${STATIC_LIBS} ${SYSTEM_LIBS} -pthread -lm)
else()
	target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE -Wl,--start-group ${STATIC_LIBS} -Wl,--end-group ${SYSTEM_LIBS} -pthread -lm)
endif()


install(TARGETS ${CMAKE_PROJECT_NAME})
