#! /usr/bin/env python
# encoding: utf-8
# mittorn, 2018

from waflib import Logs, TaskGen, Utils
from waflib.extras import pthread
import os
from copy import copy

top = '.'

FFMPEG_CHECK_FRAGMENT='''
#include <libswresample/swresample.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
#include <libavutil/avutil.h>
int main(int argc, char **argv)
{
	swresample_version();
	avformat_version();
	avcodec_version();
	swscale_version();
	avutil_version();
	return 0;
}
'''

CURL_CHECK_FRAGMENT='''
#include <curl/curl.h>
int main(int argc, char **argv)
{
	CURL *easy = curl_easy_init();
	return 0;
}
'''

frameworks = ['Foundation', 'UIKit', 'QuartzCore', 'GameController', 'SystemConfiguration', 'CFNetwork', 'AVFoundation', 'CoreGraphics']

@TaskGen.extension('.m')
def m_hook(self, node):
	return self.create_compiled_task('c', node)

def options(opt):
	grp = opt.add_option_group('Engine options')

	grp.add_option('--enable-fbdev', action = 'store_true', dest = 'FBDEV_SW', default = False,
		help = 'build fbdev-only software-only engine')

	grp.add_option('--enable-custom-swap', action = 'store_true', dest = 'CUSTOM_SWAP', default = False,
		help = 'enable custom swap allocator. For devices with no swap support')

	grp.add_option('--use-sdl1', action = 'store_true', dest = 'SDL12', default = False,
		help = 'enable using SDL1.2 instead of SDL2 (not supported or recommended) [default: %(default)s]')

	grp.add_option('--enable-static-binary', action = 'store_true', dest = 'STATIC', default = False,
		help = 'build static binary(not recommended, --single-binary required) [default: %(default)s]')

	grp.add_option('--enable-engine-fuzz', action = 'store_true', dest = 'ENGINE_FUZZ', default = False,
		help = 'add LLVM libFuzzer [default: %(default)s]' )

	grp.add_option('--enable-ffmpeg', action = 'store_true', dest = 'FFMPEG', default = False,
		help = 'enable ffmpeg based movie playback [default: %(default)s')

	grp.add_option('--enable-ffmpeg-dlopen', action = 'store_true', dest = 'FFMPEG_DLOPEN', default = False,
		help = 'load ffmpeg libraries in runtime [default: %(default)s]')

	grp.add_option('--disable-curl', action = 'store_false', dest = 'CURL', default = False,
		help = 'enable curl-based HTTP downloader [default: %(default)s]')

	opt.load('sdl2')

def find_sdl(conf):
	err_msg = '%s not available! If you want to build dedicated server, specify --dedicated'
	if conf.env.DEST_OS in ['nswitch', 'psvita']:
		err_msg = '%s not available!'

	conf.load('sdl2')
	if conf.options.SDL3:
		if not conf.env.HAVE_SDL3:
			conf.fatal(err_msg % 'SDL3')
		conf.env.XASH_SDL = 3
	else:
		if not conf.env.HAVE_SDL2:
			conf.fatal(err_msg % 'SDL2')
		conf.env.XASH_SDL = 2

def configure(conf):
	# Common dependencies, will be linked to both dedicated server and client
	if conf.env.DEST_OS == 'linux':
		conf.check_cc(lib='rt')
		if conf.env.MAGX:
			conf.define('XASH_CRASHHANDLER', 0)
	elif conf.env.DEST_OS == 'haiku':
		conf.env.LIB_HAIKU = ['network']
		conf.env.LIBPATH_HAIKU = ['/boot/system/lib']
	elif conf.env.DEST_OS == 'wasi':
		conf.env.CFLAGS += ['-mllvm', '-wasm-enable-sjlj']
	elif conf.env.DEST_OS == 'sunos':
		conf.check_cc(lib='socket')
	elif conf.env.DEST_OS == 'dos':
		conf.options.STATIC = True

	if conf.options.ENGINE_FUZZ:
		conf.env.append_unique('CFLAGS', '-fsanitize=fuzzer-no-link')
		conf.env.append_unique('LINKFLAGS', '-fsanitize=fuzzer')

	# Client-only dependencies
	if conf.env.CLIENT:
		if conf.env.DEST_OS in ['nswitch', 'psvita']:
			extra_libs = ['-lm']
			if conf.env.DEST_OS == 'psvita':
				extra_libs = ['-lstdc++', '-lm', '-lSceShaccCgExt', '-lSceShaccCg_stub', '-ltaihen_stub', '-lSceKernelDmacMgr_stub']

			conf.env.append_unique('CXXFLAGS', ['-Wl,--no-undefined'])
			conf.env.append_unique('CFLAGS', ['-Wl,--no-undefined'])

			conf.env.LDFLAGS += extra_libs
			find_sdl(conf)
			for lib in extra_libs: conf.env.LDFLAGS.remove(lib)

			if conf.env.DEST_OS == 'nswitch': # remove libstdc++ linking from SDL2, we link it later
				conf.env.LIB_SDL2.remove('stdc++')
		elif conf.env.DEST_OS == 'linux' and conf.options.FBDEV_SW:
			conf.check_cc(lib='asound')
		elif conf.options.SDL12: # TODO: move to sdl2.py
			conf.check_cfg(package='sdl', args='--cflags --libs', uselib_store='SDL1')
			conf.env.XASH_SDL = 1
			conf.env.HAVE_SDL1 = True
		else:
			find_sdl(conf)


	if conf.options.STATIC:
		conf.env.STATIC = True
		conf.define('XASH_NO_LIBDL', 1)

	if not conf.env.DEST_OS in ['win32', 'android']:
		conf.check_pthreads(mode='c')
	
	if conf.env.IOS:
		for i in frameworks :
			conf.check(features='c cprogram', framework=i, uselib_store=i, msg='Checking for %s framework' % i)

	conf.define('ENGINE_DLL', 1)

	if conf.options.FFMPEG:
		pkgconf_args = '--cflags' if conf.options.FFMPEG_DLOPEN else '--cflags --libs'
		features = 'c' if conf.options.FFMPEG_DLOPEN else 'c cprogram'

		# add ffmpeg libraries into single uselib package
		conf.check_cfg(package='libswresample', uselib_store='SWRESAMPLE', args=pkgconf_args)
		conf.check_cfg(package='libavformat', uselib_store='AVFORMAT', args=pkgconf_args)
		conf.check_cfg(package='libavcodec', uselib_store='AVCODEC', args=pkgconf_args)
		conf.check_cfg(package='libswscale', uselib_store='SWSCALE', args=pkgconf_args)
		conf.check_cfg(package='libavutil', uselib_store='AVUTIL', args=pkgconf_args)

		# validate ffmpeg libs installation
		conf.check(features=features, fragment=FFMPEG_CHECK_FRAGMENT, use='SWRESAMPLE AVCODEC AVFORMAT AVUTIL SWSCALE', msg='Checking for ffmpeg sanity')

		conf.env.FFMPEG = True
		conf.define('HAVE_FFMPEG', True)
		conf.define_cond('XASH_FFMPEG_DLOPEN', conf.options.FFMPEG_DLOPEN)

	if conf.options.CURL:
		pkgconf_args = '--cflags --libs'
		features = 'c cprogram'

		# TODO: when dlopen curl is implemented, we might not need this check
		# as we can safely bundle curl headers as curl never breaks API/ABI
		conf.check_cfg(package='libcurl', uselib_store='CURL', args=pkgconf_args)

		conf.check(features=features, fragment=CURL_CHECK_FRAGMENT, use='CURL', msg='Checking for curl sanity')

		conf.env.CURL=True
		conf.define('HAVE_CURL', True)

	conf.define_cond('XASH_STATIC_LIBS', conf.env.STATIC_LINKING)
	conf.define_cond('XASH_CUSTOM_SWAP', conf.options.CUSTOM_SWAP)
	conf.define_cond('PSAPI_VERSION', conf.env.DEST_OS == 'win32') # will be defined as 1

	for refdll in conf.refdlls:
		refdll.register_define(conf)

def build(bld):
	# public includes for renderers and utils use
	bld(name = 'engine_includes', export_includes = '. common common/imagelib', use = 'filesystem_includes')

	libs = ['engine_includes', 'public', 'werror', 'backtrace_custom', 'library_suffix', 'build_vcs']
	includes = ['server', 'client', 'client/vgui', 'common/soundlib', 'platform']

	# basic build: dedicated only
	source = bld.path.ant_glob(['common/*.c', 'common/imagelib/*.c', 'common/soundlib/*.c', 'server/*.c'])

	# include platform-specific sources, this shall not fail if directory doesn't exist
	source += bld.path.ant_glob('platform/%s/*.c' % bld.env.DEST_OS)

	# Android _is_ Linux based, after all
	if bld.env.DEST_OS == 'android':
		source += bld.path.ant_glob('platform/linux/*.c')

	# include common POSIX conformant code
	if bld.env.DEST_OS not in ['win32', 'dos']:
		source += bld.path.ant_glob('platform/posix/*.c')
	if bld.env.IOS:
		source += bld.path.ant_glob('platform/ios/*.c')
		source += bld.path.ant_glob('platform/ios/*.m')
		includes += bld.path.ant_glob('platform/ios')
	
	# include sources for optional features
	if bld.get_define('XASH_CUSTOM_SWAP'):
		source += ['platform/misc/kmalloc.c', 'platform/misc/sbrk.c']

	if bld.get_define('XASH_STATIC_LIBS'):
		source += ['platform/misc/lib_static.c']

	if bld.get_define('HAVE_CURL'):
		source += ['common/http/net_http_curl.c']
		libs += ['CURL']
	else:
		source += ['common/http/net_http_xash.c']

	if bld.env.DEST_OS == 'win32':
		libs += ['USER32', 'SHELL32', 'GDI32', 'ADVAPI32', 'DBGHELP', 'PSAPI', 'WS2_32']
	elif bld.env.DEST_OS == 'nswitch':
		libs += ['SOLDER']
		# HACK: link in the entirety of libstdc++ so that dynamic libs could use all of it without manual exporting
		# we can't do this right away because std::filesystem will complain about not having pathconf(),
		# which we have defined in sys_nswitch.c
		bld.env.LDFLAGS += ['-v', '-Wl,--whole-archive', '-lstdc++', '-Wl,--no-whole-archive', '-lm']
	elif bld.env.DEST_OS == 'psvita':
		libs += ['VRTLD']
		# HACK: link in the entirety of libstdc++ so that dynamic libs could use all of it without manual exporting
		# also link in all the funky dependencies that aren't in SDL2's LDFLAGS
		bld.env.LDFLAGS += ['-Wl,--whole-archive', '-lstdc++', '-lpthread', '-Wl,--no-whole-archive',
			'-lm', '-lSceShaccCgExt', '-lkubridge_stub', '-ltaihen_stub', '-lSceShaccCg_stub', '-lSceKernelModulemgr_stub', '-lSceSblSsMgr_stub', '-lSceVshBridge_stub', '-lSceKernelDmacMgr_stub', '-lSceLibKernel_stub',
		]
	else: # POSIX
		libs += ['M', 'RT', 'PTHREAD', 'ASOUND', 'HAIKU', 'MAGX', 'LOG', 'SOCKET']
		if not bld.env.STATIC:
			libs += ['DL']

	if bld.env.SERVER:
		# TODO: avoid possible name collision when client is built without launcher
		# but dedicated server is enabled. They're both called 'xash' in this case
		server_source = copy(source)
		server_libs = copy(libs)
		bld.program(
			source = server_source,
			target = 'xash',
			use = server_libs,
			includes = includes,
			defines = 'XASH_ENABLE_MAIN=1 XASH_DEDICATED=1',
			rpath = bld.env.DEFAULT_RPATH,
			install_path = bld.env.BINDIR,
		)

		# the execution stucks on macOS, disable for now
		if bld.env.TESTS and Utils.unversioned_sys_platform() != 'darwin':
			fs_tg = bld.get_tgen_by_name('filesystem_stdio')
			fs_tg.post()
			tg = bld.program(
				source = server_source,
				target = 'xash_tests_dedicated',
				use = server_libs,
				includes = includes,
				features = 'test',
				defines = 'XASH_ENABLE_MAIN=1 XASH_DEDICATED=1 XASH_ENGINE_TESTS=1',
				rpath = bld.env.DEFAULT_RPATH,
				install_path = None,
				ut_str = '${SRC[0].abspath()} -dev 2 -runtests',
			)
			tg.ut_paths = fs_tg.link_task.outputs[0].parent.abspath() + os.pathsep

	if bld.env.CLIENT:
		defines = []
		if bld.env.XASH_SDL:
			libs += ['SDL%d' % bld.env.XASH_SDL]
			source += bld.path.ant_glob(['platform/sdl%d/*.c' % bld.env.XASH_SDL])
			defines += ['XASH_SDL=%d' % bld.env.XASH_SDL]

		if bld.get_define('HAVE_FFMPEG'):
			libs.append('SWRESAMPLE')
			libs.append('AVCODEC')
			libs.append('AVFORMAT')
			libs.append('AVUTIL')
			libs.append('SWSCALE')

		# add client files
		if not bld.env.DEDICATED:
			source += bld.path.ant_glob('client/**/*.c')
			libs += ['bzip2', 'MultiEmulator', 'opus', 'opusfile', 'vorbis', 'vorbisfile']

		# Android port is linked differently
		if bld.env.DEST_OS == 'android':
			f = bld.shlib
			install_path = bld.env.LIBDIR
			defines += ['XASH_ENABLE_MAIN=1', 'XASH_SDLMAIN=1']
		elif not bld.env.LAUNCHER:
			f = bld.program
			install_path = bld.env.BINDIR
			defines += ['XASH_ENABLE_MAIN=1']
		else:
			f = bld.shlib
			install_path = bld.env.LIBDIR

		if bld.env.IOS:
			libs += frameworks
			defines += ['XASH_SDLMAIN=1']

		if bld.env.DEST_OS in ['nswitch', 'psvita', 'emscripten']:
			install_path = None

		linkflags = []

		if bld.env.DEST_OS == 'emscripten':
			linkflags = ['-sINITIAL_MEMORY=134217728', '-sALLOW_MEMORY_GROWTH=1', '-sSTACK_SIZE=16777216']

			linkflags += ['-sASYNCIFY=1']

			node = bld.srcnode.find_node('rodir')
			if not node:
				bld.fatal('Put game data into rodir folder in source tree root')
			linkflags += ['--preload-file', '%s@/rodir' % node.path_from(bld.bldnode)]

		f(source = source,
			target = 'xash',
			includes = includes,
			features = 'cxx c',
			use = libs,
			defines = defines,
			install_path = install_path,
			special_install_path = bld.env.BINDIR,
			nacp = 'platform/nswitch/xash3d-fwgs.nacp',
			icon = 'platform/nswitch/icon.jpg',
			sce_sys = 'platform/psvita/sce_sys',
			title_id = 'XASH10000',
			app_name = 'xash3d-fwgs',
			rpath = bld.env.DEFAULT_RPATH,
			linkflags = linkflags,
		)

		# the execution stucks on macOS, disable for now
		if bld.env.TESTS and Utils.unversioned_sys_platform() != 'darwin':
			fs_tg = bld.get_tgen_by_name('filesystem_stdio')
			fs_tg.post()
			tg = bld.program(source = source,
				target = 'xash_tests',
				includes = includes,
				features = 'cxx c test',
				use = libs,
				defines = defines + ['XASH_ENABLE_MAIN=1', 'XASH_ENGINE_TESTS=1'],
				install_path = None,
				rpath = bld.env.DEFAULT_RPATH,
				linkflags = linkflags,
				ut_str = '${SRC[0].abspath()} -dev 2 -runtests',
			)
			paths = [fs_tg.link_task.outputs[0].parent.abspath()]

			if bld.env.LIBPATH_SDL2:
				paths += bld.env.LIBPATH_SDL2

			tg.ut_paths = os.pathsep.join(paths) + os.pathsep

			# taken from dyld(1) man-page
			if Utils.unversioned_sys_platform() == 'darwin':
				if not hasattr(tg, 'ut_env'):
					setattr(tg, 'ut_env', dict(os.environ))
				tg.ut_env['DYLD_FALLBACK_FRAMEWORK_PATH'] = '/Library/Frameworks:/System/Library/Frameworks'
