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

from waflib import Logs
from waflib.extras import pthread
import os

top = '.'

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('--disable-async-resolve', action = 'store_true', dest = 'NO_ASYNC_RESOLVE', default = False,
		help = 'disable multithreaded operations(asynchronous name resolution)')

	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('--enable-legacy-sdl', action = 'store_true', dest = 'SDL12', default = False,
		help = 'enable using SDL1.2 instead of SDL2(not recommended) [default: %default]')

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

	grp.add_option('--enable-engine-tests', action = 'store_true', dest = 'ENGINE_TESTS', default = False,
		help = 'embed tests into the engine, jump into them by -runtests command line switch [default: %default]')

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

	opt.load('sdl2')

def configure(conf):
	# check for dedicated server build
	if conf.options.DEDICATED:
		if conf.env.DEST_OS == 'linux':
			conf.check_cc(lib='rt')
		conf.define('XASH_DEDICATED', 1)
	elif conf.env.DEST_OS == 'dos':
		conf.options.STATIC = True
		conf.options.NO_ASYNC_RESOLVE = True
		if not conf.check_cc( fragment='int main(){ int i = socket();}', lib = 'wattcpwl', mandatory=False ):
			conf.define('XASH_NO_NETWORK',1)
	elif conf.env.DEST_OS == 'nswitch':
		# re-enable undefined reference errors
		conf.env.CXXFLAGS += ['-Wl,--no-undefined']
		conf.env.CFLAGS += ['-Wl,--no-undefined']
		# allow the SDL2 sanity check to complete properly by linking in libstdc++ and lm normally
		conf.env.LDFLAGS += ['-lstdc++', '-lm']
		conf.load('sdl2')
		if not conf.env.HAVE_SDL2:
			conf.fatal('SDL2 not availiable! Install switch-sdl2!')
		conf.define('XASH_SDL', 2)
		# then remove them to avoid them getting linked to shared objects
		conf.env.LDFLAGS.remove('-lstdc++')
		conf.env.LDFLAGS.remove('-lm')
	elif conf.env.DEST_OS == 'psvita':
		# allow the SDL2 sanity check to complete properly by linking in some deps missing from the pkg-config file
		extra_libs = ['-lstdc++', '-lm', '-lSceShaccCgExt', '-lSceShaccCg_stub', '-ltaihen_stub', '-lSceKernelDmacMgr_stub']
		conf.env.LDFLAGS += extra_libs
		conf.load('sdl2')
		if not conf.env.HAVE_SDL2:
			conf.fatal('SDL2 not availiable! Install switch-sdl2!')
		conf.define('XASH_SDL', 2)
		# then remove them to avoid them getting linked to shared objects
		for lib in extra_libs:
			conf.env.LDFLAGS.remove(lib)
	elif conf.options.FBDEV_SW:
		# unused, XASH_LINUX without XASH_SDL gives fbdev & alsa support
		# conf.define('XASH_FBDEV', 1)
		conf.check_cc( lib = 'asound' )
		conf.check_cc( lib = 'rt' )
	elif conf.options.SDL12:
		conf.define('XASH_SDL', 12)
		conf.check_cfg(package='sdl', args='--cflags --libs', uselib_store='SDL2' )
		if conf.env.DEST_OS == 'linux':
			conf.check_cc( lib='rt' )
		conf.env.HAVE_SDL2 = True
	else:
		conf.load('sdl2')
		if not conf.env.HAVE_SDL2:
			conf.fatal('SDL2 not available! If you want to build dedicated server, specify --dedicated')
		conf.define('XASH_SDL', 2)

	if conf.env.DEST_OS == 'haiku':
		conf.env.LIB_HAIKU = ['network']
		conf.env.LIBPATH_HAIKU = ['/boot/system/lib']

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

	if not conf.env.DEST_OS in ['win32', 'android'] and not conf.options.NO_ASYNC_RESOLVE:
		conf.check_pthreads()

	if hasattr(conf.options, 'DLLEMU'):
		conf.define_cond('XASH_DLL_LOADER', conf.options.DLLEMU)

	if conf.env.MAGX:
		conf.define('XASH_CRASHHANDLER', 0)

	conf.env.ENGINE_TESTS = conf.options.ENGINE_TESTS

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

	conf.define_cond('XASH_ENGINE_TESTS', conf.env.ENGINE_TESTS)
	conf.define_cond('XASH_STATIC_LIBS', conf.env.STATIC_LINKING)
	conf.define_cond('XASH_CUSTOM_SWAP', conf.options.CUSTOM_SWAP)
	conf.define_cond('SINGLE_BINARY', conf.env.SINGLE_BINARY)
	conf.define_cond('XASH_NO_ASYNC_NS_RESOLVE', conf.options.NO_ASYNC_RESOLVE)
	conf.define_cond('SUPPORT_BSP2_FORMAT', conf.options.SUPPORT_BSP2_FORMAT)
	conf.define_cond('XASH_64BIT', conf.env.DEST_SIZEOF_VOID_P != 4)
	conf.define_cond('DBGHELP', conf.env.DEST_OS == 'win32')
	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')

	is_cxx_link = False
	libs = [ 'engine_includes', 'public', 'dllemu' ]

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

	if bld.env.ENGINE_TESTS:
		source += bld.path.ant_glob(['tests/*.c'])

	if bld.env.DEST_OS == 'win32':
		libs += ['USER32', 'SHELL32', 'GDI32', 'ADVAPI32', 'DBGHELP', 'PSAPI', 'WS2_32' ]
		source += bld.path.ant_glob(['platform/win32/*.c'])
	elif bld.env.DEST_OS not in ['dos', 'nswitch', 'psvita']: #posix
		libs += [ 'M', 'RT', 'PTHREAD', 'ASOUND']
		if not bld.env.STATIC:
			libs += ['DL']
		source += bld.path.ant_glob(['platform/posix/*.c'])

	if bld.env.DEST_OS == 'linux':
		source += bld.path.ant_glob(['platform/linux/*.c'])

	if bld.env.DEST_OS == 'irix':
		source += bld.path.ant_glob(['platform/irix/*.c'])

	if bld.env.DEST_OS == 'dos':
		source += bld.path.ant_glob(['platform/dos/*.c'])
		source += bld.path.ant_glob(['platform/stub/s_stub.c'])

	if bld.env.DEST_OS == 'haiku':
		libs.append('HAIKU')

	if bld.get_define('XASH_CUSTOM_SWAP'):
		source += bld.path.ant_glob(['platform/misc/kmalloc.c', 'platform/misc/sbrk.c'])

	if bld.env.STATIC_LINKING:
		source += bld.path.ant_glob(['platform/misc/lib_static.c'])
		is_cxx_link = True

	if bld.env.HAVE_SDL2:
		libs.append('SDL2')
		source += bld.path.ant_glob(['platform/sdl/*.c'])

	if bld.env.MAGX:
		libs.append('MAGX')
		source += bld.path.ant_glob(['platform/magx/*.cpp'])
		is_cxx_link = True

	if bld.env.DEST_OS == 'android':
		libs += ['LOG']
		source += bld.path.ant_glob(['platform/android/*.cpp', 'platform/android/*.c', 'platform/linux/*.c'])

	if bld.env.DEST_OS == 'nswitch':
		libs += [ 'SOLDER' ]
		source += bld.path.ant_glob(['platform/posix/*.c'])
		source += bld.path.ant_glob(['platform/nswitch/*.c'])
		# 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 += ['-Wl,--whole-archive', '-lstdc++', '-Wl,--no-whole-archive', '-lm']

	if bld.env.DEST_OS == 'psvita':
		libs += [ 'VRTLD' ]
		source += bld.path.ant_glob(['platform/posix/*.c'])
		source += bld.path.ant_glob(['platform/psvita/*.c'])
		# 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'
		]

	# add client files
	if not bld.env.DEDICATED:
		source += bld.path.ant_glob([
			'client/*.c',
			'client/vgui/*.c',
			'client/avi/*.c'])
		libs += ['opus']

	includes = ['server', 'client', 'client/vgui' ]

	# Switch and PSVita have custom parameters
	if bld.env.DEST_OS in ['nswitch', 'psvita']:
		bld(source = source,
			target = 'xash',
			features = 'c cxxprogram',
			includes = includes,
			use = libs,
			install_path = None,
			nro_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'
		)
	else:
		if bld.env.SINGLE_BINARY:
			install_path = bld.env.BINDIR
			program = 'cxxprogram' if is_cxx_link else 'cprogram'
			if bld.env.STATIC:
				program += '_static'
			features = ['c', program]
		else:
			install_path = bld.env.LIBDIR
			features = ['c', 'cxxshlib' if is_cxx_link else 'cshlib']

		bld(source   = source,
			target   = 'xash',
			features = features,
			includes = includes,
			use      = libs,
			install_path = install_path,
			subsystem = bld.env.MSVC_SUBSYSTEM,
			rpath = bld.env.DEFAULT_RPATH,
		)
