# vim: set ts=2 sw=2 tw=99 noet ft=python:
import os
import ambuild.osutil as osutil
from ambuild.command import SymlinkCommand

def BuildEverything():
	if AMBuild.target['platform'] not in ['linux', 'windows', 'darwin']:
		return

	BuildExtension();

def BuildExtension():
	compiler = SM.DefaultCompiler()

	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.sourceFolder, 'extension'))
	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.sourceFolder, 'extension', 'sdk'))

	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.cache['SOURCEMOD15'], 'public'))
	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.cache['SOURCEMOD15'], 'public', 'extensions'))
	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.cache['SOURCEMOD15'], 'public', 'sourcepawn'))

	compiler['CXXINCLUDES'].append(os.path.join(AMBuild.sourceFolder, 'google-breakpad', 'src'))

	if AMBuild.target['platform'] == 'linux':
		compiler['POSTLINKFLAGS'].append('-lstdc++')
		compiler['POSTLINKFLAGS'].append('-pthread')
	elif AMBuild.target['platform'] == 'darwin':
		compiler['POSTLINKFLAGS'].extend(['-framework', 'CoreServices'])

	name = 'accelerator.ext'
	extension = AMBuild.AddJob(name)
	binary = Cpp.LibraryBuilder(name, AMBuild, extension, compiler)

	binary.AddSourceFiles('extension', [
		'extension.cpp',
		'MemoryDownloader.cpp',
		'sdk/smsdk_ext.cpp'
	])

	if AMBuild.target['platform'] in ['linux', 'darwin']:
		link = os.path.join(AMBuild.outputFolder, extension.workFolder, 'libbreakpad_client.a')
		if AMBuild.target['platform'] == 'linux':
			target = os.path.join(AMBuild.outputFolder, 'google-breakpad', 'src', 'client', 'linux', 'libbreakpad_client.a')
		else:
			target = os.path.join(AMBuild.outputFolder, SM.breakpadWorkFolder, 'libbreakpad_client.a')

		try:
			os.lstat(link)
		except:
			extension.AddCommand(SymlinkCommand(link, target))

		binary.AddObjectFiles(['libbreakpad_client.a'])

	elif AMBuild.target['platform'] == 'windows':
		libs = ['exception_handler', 'common', 'crash_generation_client']
		for lib in libs:
			path = os.path.join(AMBuild.sourceFolder, 'google-breakpad', 'src', 'client', 'windows', 'handler', 'Release', 'lib', lib + '.lib')
			if os.path.isfile(path):
				binary.RelinkIfNewer(path)
			binary['POSTLINKFLAGS'].extend([path])

	SM.AutoVersion('extension', binary)
	SM.ExtractDebugInfo(extension, binary)

	binary.SendToJob()

AMBuild.Include(os.path.join('google-breakpad', 'AMBuilder'), {'SM': SM})
BuildEverything()
