#
# Copyright (c) 2006-2007, Reid Nichol
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
#     * Redistributions of source code must retain the above
#       copyright notice, this list of conditions and the following
#       disclaimer.
#     * Redistributions in binary form must reproduce the above
#       copyright notice, this list of conditions and the following
#       disclaimer in the documentation and/or other materials
#       provided with the distribution.
#     * Neither the name of Fireflylabs.ca nor the names of its
#       contributors may be used to endorse or promote products
#       derived from this software without specific prior written
#       permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

import os, sys

# this is where our build support is for all subprojects
commonDir = os.curdir + os.sep + os.pardir + os.sep + os.pardir + os.sep + "common"
sys.path.append(os.path.realpath(commonDir + os.sep + "build"))

from build_support import *


# get where we are
platform = sys.platform

# SUPPORTED PLATFORMS
#
supported_platforms = ['darwin', 'openbsd4', 'linux2']


if platform not in supported_platforms:
	print "Platform '" + platform + "' not supported"
	Exit(1)

# now that we know we belong here, we build the env, etc
if platform == 'win32':
	env = Environment(ENV=os.environ)
else:
	env = Environment()

# for win32 we prefer mingw
if platform == 'win32':
	Tool('mingw')(env)


# SECTION: OPTIONS
#
# platform should NEVER be used outside this section
options = Options()

# our build type.  When adding another platform, it must be
# added in the list.
options.Add('build_type', 'Type of build to perform - defaults to platform (macosx|darwin|openbsd4|linux2)', platform)

# setup the install location
#
# darwin:  /opt/local
# macosx:  /Applications
# openbsd: /usr/local
# win32:   C:\\
options.Add('prefix', 'Location to install')

# which threading library to use
if platform in ['darwin', 'macosx', 'openbsd4', 'linux2']:
	options.Add('with_threads', 'Thread library to use (pthread|pthread_dynamic)', 'pthread')
elif platform == 'win32':
	# ??? (pthreads on win32 is LGPL'd) http://sourceware.org/pthreads-win32/
	options.Add('with_threads', 'Thread library to use (pthread|pthread_dynamic)', 'pthread_dynamic')

# which audio library to use
if platform in ['darwin', 'macosx', 'openbsd4', 'win32', 'linux2']:
	options.Add('with_audio', 'Audio library to use', 'openal')


options.Update(env)
#Help(helpText(options, env))


# SECTION: VAR CREATION

# start with an empty sourcefile list
source_files = []
# an empty libpath
libpath      = []
# an empty libs list
libs         = []
# an empty frameworks list
frameworks   = []
# an empty cpppath
cpppath      = []
# an empty cflags
cflags       = []
# an empty ldflags
ldflags      = []


# for macosx
if env['build_type'] == 'macosx':
	frameworkpathbase = '/System/Library/Frameworks'
	cflags.append('-D_MACOSX')
elif env['build_type'] == 'darwin':
	# we use the OSX system Python as MacPorts uses site.py
	# from that as well.
	frameworkpathbase = '/System/Library/Frameworks'
	cflags.append('-D_DARWIN')
elif env['build_type'] == 'openbsd4':
	cflags.append('-D_OPENBSD')
elif env['build_type'] == 'linux2':
	cflags.append('-D_LINUX2')

# SECTION: CORE SOURCE

# we then add in the core source file(s)
source_files[len(source_files):] = ['main.c', 'render_test.c', 'keyboard_noresponse.c',\
			'mouse_noresponse.c', 'state.c', 'ai.c', 'sync_test.c',\
			'render_control.c', 'simulation.c', 'simulation_test.c']

# for everyone we want
#cflags[len(cflags):] = ['-Wall', '-O2', '-g']
cflags[len(cflags):] = ['-Wall']


# SECTION: SETUP LIB/INCLUDE/FRAMEWORKS/etc


# win32 needs a wrapper to provide dlfcn functionality
if env['build_type'] == 'win32':
	source_files.append('loadlib.c')


# construct our general include/lib dir
if env['build_type'] == 'darwin':
	libpath.append('/opt/local/lib')
	cpppath.append('/opt/local/include')

elif env['build_type'] == 'macosx':
	# because macosx has both frameworks and libs
	# we need this as well
	libpath.append('/usr/lib')
	libpath.append('/usr/local/lib')
	cpppath.append('/usr/include')
	cpppath.append('/usr/local/include')

elif env['build_type'] == 'openbsd4':
	libpath.append('/usr/lib')
	libpath.append('/usr/local/lib')
	cpppath.append('/usr/local/include')
	cpppath.append('/usr/include')

elif env['build_type'] == 'linux2':
	libpath.append('/usr/lib')
	libpath.append('/usr/local/lib')
	cpppath.append('/usr/local/include')
	cpppath.append('/usr/include')

#elif env['build_type'] == 'win32':
#	???


# To add Python in the mix, we need link options.  But, those
# are different for any given build.  Fortunately:
# http://docs.python.org/ext/link-reqs.html
# gives the answer.
# Unfortunately, it doesn't seem to work on OSX.  So, I manually
# set the vars there.
if env['build_type'] == 'darwin':
	libpath.append(frameworkpathbase + '/Python.framework')
	cpppath.append(frameworkpathbase + '/Python.framework/Headers')
	frameworks.append('Python')
	ldflags[len(ldflags):] = ['-u', '_PyMac_Error']

elif env['build_type'] == 'macosx':
	libpath.append(frameworkpathbase + '/Python.framework')
	cpppath.append(frameworkpathbase + '/Python.framework/Headers')
	frameworks[len(frameworks):] = ['System', 'Python', 'CoreServices', 'Foundation']
	ldflags[len(ldflags):] = ['-u', '__dummy', '-u', '_PyMac_Error']

elif env['build_type'] == 'openbsd4':
	import distutils.sysconfig
	for opt in Split(distutils.sysconfig.get_config_var('LINKFORSHARED')):
		ldflags.append(opt)

	cpppath.append('/usr/local/include/python' + sys.version[:3])
	libs.append('python' + sys.version[:3])

	# necessary for python on OpenBSD
	libs.append('util')

elif env['build_type'] == 'linux2':
	import distutils.sysconfig
	for opt in Split(distutils.sysconfig.get_config_var('LINKFORSHARED')):
		ldflags.append(opt)

	cpppath.append('/usr/include/python' + sys.version[:3])
	libs.append('python' + sys.version[:3])

# we now add the directory where the AI is
# NOTE: The should be in an developer target.  Perhaps
#       something like dev=(0|1)
env.AppendUnique(CCFLAGS = ['-DAIDIRECTORY=\\"' + os.path.realpath(os.curdir + os.sep + 'ai') + '\\"'])


# the GL/GLUT include/lib path and libs
if env['build_type'] == 'darwin':
	# GL
	libpath.append('/usr/X11R6/lib')
	cpppath[len(cpppath):] = ['/usr/X11R6/include', '/usr/X11R6/include/GL']
	libs[len(libs):] = ['GL', 'GLU']

	# GLUT
	libpath.append('/opt/local/lib')
	cpppath.append('/opt/local/include/GL')
	libs.append('glut')

elif env['build_type'] == 'macosx':
	# GL
	libpath.append(frameworkpathbase + '/OpenGL.framework')
	cpppath.append(frameworkpathbase + '/OpenGL.framework/Headers')
	frameworks.append('OpenGL')

	# GLUT
	libpath.append(frameworkpathbase + '/GLUT.framework')
	cpppath.append(frameworkpathbase + '/GLUT.framework/Headers')
	frameworks.append('GLUT')

elif env['build_type'] == 'openbsd4':
	# GL
	libpath.append('/usr/X11R6/lib')
	cpppath[len(cpppath):] = ['/usr/X11R6/include', '/usr/X11R6/include/GL']
	libs[len(libs):] = ['GL', 'GLU']

	# GLUT
	libpath.append('/usr/local/lib')
	cpppath.append('/usr/local/include/GL')
	libs.append('glut')

	# OpenBSD needs some extra libs
	libs[len(libs):] = ['m', 'Xmu', 'Xi', 'Xext', 'X11']

elif env['build_type'] == 'linux2':
	# GL
	libpath.append('/usr/X11R6/lib')
	cpppath[len(cpppath):] = ['/usr/X11R6/include', '/usr/X11R6/include/GL']
	libs[len(libs):] = ['GL', 'GLU']

	# GLUT
	libpath.append('/usr/lib')
	cpppath.append('/usr/include/GL')
	libs.append('glut')

#elif platform == 'win32':
#	# ???
#	continue

if env['build_type'] == 'macosx':
	# we build a universal binary for OSX
	cflags.append('-isysroot/Developer/SDKs/MacOSX10.4u.sdk')
	ldflags.append('-isysroot/Developer/SDKs/MacOSX10.4u.sdk')
	cflags[len(cflags):] = ['-arch', 'i386', '-arch', 'ppc']
	ldflags[len(ldflags):] = ['-arch', 'i386', '-arch', 'ppc']

# SECTION: SETUP THREADING
if env['with_threads'] == 'pthread_dynamic':
	# add CCFLAGS
	env.AppendUnique(CCFLAGS = ['-D__THREADS_PTHREAD_DYNAMIC__'])

	# don't add in libs as they are loaded at run time

	# add the source file
	source_files.append('threads_pthread_dynamic.c')

elif env['with_threads'] == 'pthread':
	# add CCFLAGS
	env.AppendUnique(CCFLAGS = ['-D__THREADS_PTHREAD__'])

	# add libs
	env.AppendUnique(LIBS = ['pthread'])

	# add the source file
	source_files.append('threads_pthread.c')


# SECTION: SETUP AUDIO
if env['with_audio'] == 'none':
	env.AppendUnique(CCFLAGS = ['-D__AUDIO_NONE__'])

	source_files.append('audio_none.c')

elif env['with_audio'] == 'openal':
	env.AppendUnique(CCFLAGS = ['-D__AUDIO_OPENAL__'])

	if env['build_type'] == 'macosx':
		cpppath.append(frameworkpathbase + '/OpenAL.framework/Headers')
	elif env['build_type'] == 'darwin':
		cpppath.append('/opt/local/include/openal')
	elif env['build_type'] == 'openbsd4':
		cpppath.append('/usr/local/include/AL')
		# OpenBSD OSS emulation (Linux) lib required by OpenAL
		libs.append('ossaudio')
	elif env['build_type'] == 'linux2':
		cpppath.append('/usr/include/AL')

	source_files.append('audio_openal.c')


# SECTION: SET VARS
env.AppendUnique(LIBPATH    = libpath)
env.AppendUnique(CPPPATH    = cpppath)
env.AppendUnique(LIBS       = libs)
env.AppendUnique(FRAMEWORKS = frameworks)
env.AppendUnique(CCFLAGS    = cflags)
env.AppendUnique(LINKFLAGS  = ldflags)


# SECTION: BUILD

# right now we're always just making a program.  Will be change
# later for Mac OSX Bundles.
env.Program('theverse', source_files)

# a misguided attempt at making a bundle.  Need to look into
# scons build system before another attempt is made
#if env['build_type'] == 'macosx':
#	makeAppBundle("The Verse", 'theverse', {}, "")
