import os, shutil

Import('*')

#TODO: find a way to remove the .orig files astyle leaves around. Probably in
#      scons-tools/astyle.py

if env['PLATFORM'] == 'win32':
	SRC= list(set(simpleglob("*.cc")) - set(("main.cc",".\\main.cc"))) +["build_info.cc"]
else:
	SRC= list(set(simpleglob("*.cc")) - set(("main.cc","./main.cc"))) +["build_info.cc"]

srcenv=env.Clone()

Export('srcenv')

# Ordering is paramount in the SConscript calls!
#
# Each SConscript returns one or more SCons.Node(s) that will be used for
# linking the library.
#
# The final reverse() is needed because the linker scans it's parameter list
# in reverse. Do not simply reverse the order of the SConscript calls
# themselves: other things might be happening in there that profit from correct
# ordering (ordering of compilation is always controlled directly by scons
# itself, though)
#

tests = []

Export("tests")

libs=[]
def add_sconscript( submodule ):
    global libs
    lib = SConscript("%s/SConscript" % submodule )
    libs += lib

# Currently wui is doublelinked on linux we will else get undefined references
# however there should be a better solution!?!
add_sconscript('graphic')
add_sconscript('sound')
filesystem,io=SConscript('io/SConscript')
libs.extend( (filesystem,io ) )
add_sconscript('wui')
add_sconscript('network')
add_sconscript('ui_basic')
add_sconscript('ui_fsmenu')
libs+=list(SConscript('editor/SConscript'))
add_sconscript('trigger')
add_sconscript('events')
add_sconscript('ai')
add_sconscript('wui')
add_sconscript('economy')
add_sconscript('logic')
add_sconscript('map_io')
add_sconscript('game_io')
add_sconscript('profile')

remaining = [srcenv.Object( i.replace(".cc",""),source=i) for i in SRC ]

libs.reverse()

# Currently all tests are linked against all widelands
# libraries. It is impossible to get some classes under test
# in any other way currently
for name,sources in tests:
    testEnv.addUnitTest(name, source = sources + remaining + libs )

srcenv.Append(INDENTLIST=[
	'helper.h',
	'helper.cc',
	'journal.h',
	'journal.cc',
	'journal_exceptions.h',
	'journal_exceptions.cc',
	'main.cc',
	'wlapplication.h',
	'wlapplication.cc',
	])
indent=srcenv.astyle(source=srcenv['INDENTLIST'])
env.Alias("indent", indent)

def link_or_copy(target, source, env):
	src=source[0].get_path()
	dst=target[0].get_path()

	if os.path.lexists(dst):
		os.remove(dst)

	if 'symlink' in dir(os):
		os.symlink(src, dst)
	else:
		shutil.copy2(src, dst)

binary=srcenv.Program(target='widelands', source=["main.cc"] + remaining + libs)
if env['PLATFORM'] == 'win32':
	copybinary=srcenv.Command('#/Widelands.exe', binary, Action(link_or_copy))
else:
	copybinary=srcenv.Command('#/widelands', binary, Action(link_or_copy))

Return('copybinary')
