import os
import SCons
import glob
from SCons.Script import *
from SCons.Script.SConscript import SConsEnvironment

def PhonyTarget(env, target, action):
    env.Append(BUILDERS = { 'phony' : Builder(action = action) })
    p = env.phony(target = target, source = None)
    AlwaysBuild(p)
    return p

SConsEnvironment.PhonyTarget = PhonyTarget

global AddInitializer
def AddInitializer(f):
    initializers.append(f)

global AddCustomTest
def AddCustomTest(n, f):
    CustomTests[n] = f

global AddFinalizer
def AddFinalizer(f):
    finalizers.append(f)

global initializers
global finalizers
global CustomTests
initializers = []
finalizers = []
CustomTests = {}

__all__ = []

def makeStagingDir(stage):
	if not os.path.exists(stage):
		os.makedirs(stage)
	if not os.path.exists(os.path.join(stage, 'lib')):
		os.mkdir(os.path.join(stage, 'lib'))
	if not os.path.exists(os.path.join(stage, 'bin')):
		os.mkdir(os.path.join(stage, 'bin'))
	return os.path.realpath(stage)

# Set up extensions
extensions = glob.glob(os.path.join('scripts', '*.py'))
for ex in extensions:
    if ex != os.path.join('scripts', '__init__.py'):
	__all__.append(os.path.basename(ex[0:-3]))

def SConscripts(env, sconscripts):
    for a in sconscripts:
	env.SConscript(os.path.join(a, 'SConscript'), build_dir=os.path.join(env['BUILDDIR'], a), duplicate=0)
	env.ExtraDist(os.path.join(a, 'SConscript'))

def SetupOptions():
    opts = Options('config.py')
    opts.Add(EnumOption('BUILDCFG',
                        """Determines whether to build with debugging information or
optimizations.  Also controls whether dependencies are built in debug or
release mode.""",
                        'debug',
                        allowed_values=('debug', 'release')))

    opts.Add('DOWNLOAD_OPT',
             """Format is DOWNLOAD_OPT=package1=option,package2=option
Where 'option' is one of:
  apt-get  : prefer to install package using apt-get
  download : prefer download source tar/zip file
  bzr      : prefer to get source using 'bzr branch'
  hg       : prefer to get source using 'hg clone'
For example 'DOWNLOAD_OPT=libpng=apt-get,lightfeather=checkout,epm=download'
Otherwise default fallback order is apt-get, download, bzr, hg.
""",
             '')

    opts.Add(PathOption('BUILDDIR',
                        'Build directory',
                        '',
                        PathOption.PathAccept))

    opts.Add(PathOption('THIRDPARTY',
                        'Directory to download and compile third party dependencies',
                        '',
                        PathOption.PathAccept))

    opts.Add(PathOption('THIRDPARTY_STAGEDIR',
                        'Directory to copy results of compiling third party dependencies',
                        '',
                        PathOption.PathAccept))

    opts.Add(PathOption('STAGEDIR',
                        'Staging directory to install project files',
                        '',
                        PathOption.PathAccept))

    opts.Add(PathOption('DESTDIR',
                        'Final directory to install project files',
                        '',
                        PathOption.PathAccept))
    
    return opts

def SetupExtensions(env):
    if env['BUILDDIR'] == '':
        env['BUILDDIR'] = os.path.realpath(os.path.join(env['BUILDCFG'], 'build'))

    if env['THIRDPARTY'] == '':
        env['THIRDPARTY'] = os.path.realpath(os.path.join(env['BUILDCFG'], 'thirdparty'))

    if env['THIRDPARTY_STAGEDIR'] == '':
        env['THIRDPARTY_STAGEDIR'] = os.path.join(env['THIRDPARTY'], 'stage')

    if env['STAGEDIR'] == '':
        env['STAGEDIR'] = makeStagingDir(os.path.join(env['BUILDCFG'], 'stage'))

    if env['DESTDIR'] == '':
        env['DESTDIR'] = os.path.realpath(env['STAGEDIR'])

    for f in initializers:
	f(env)

    env.ExtraDist(extensions)
    env.ExtraDist(['scons.py', 'scons-local-0.97'], ['.pyc'])

def RunFinalizers(env):
    for f in finalizers:
	f(env)


