#
#   Copyright 2008 Glencoe Software, Inc. All rights reserved.
#   Use is subject to license terms supplied in LICENSE.txt
#

# www.scons.org based build file which builds and optionally runs
# all the examples in this directory. Each directory is its own
# context. If it contains a "SConscript", it will be called with
# the same parameters. Otherwise, all the files will be built via
# the default logic in this file. Such basic directories should
# not contain sub-directories.

# Instructions:
#
#   Environment Variables:
#
#     ICE_CONFIG=dist/etc/ice.config
#     PYTHONPATH=<location of modules to be added>
#
#     On Windows, use ";" to separate your paths, otherwise ":"
#
#   Command-line arguments:
#
#     builddir=../omero  # Path to a build directory other than ../dist
#     run=1              # Causes all the files to be executed
#     run_java=1         # Causes Java files to be executed
#     no_java=1          # Prevents building the Java files
#     run_py=1           # Causes Python files to be executed
#
#
import glob, os
_ = os.path.sep.join

#
# Reusable code
#
def env_path(key):
    """
    Reads a path from the environment and splits it into
    a list
    """
    value = os.environ.has_key(key) and os.environ[key] or []
    value = value and value.split(os.path.pathsep) or []
    return value


#
# Setup
#
platform = ARGUMENTS.get('OS', Platform())
mode = ARGUMENTS.get('mode', "debug")
link = ARGUMENTS.get("link","omero_client").split()
builddir = os.path.abspath(os.path.join(os.pardir,"dist"))
builddir = ARGUMENTS.get("builddir",builddir)
pypath  = env_path("PYTHONPATH")
if os.environ.has_key("ICE_CONFIG"):
    ice_config = os.environ["ICE_CONFIG"]
else:
    ice_config = os.path.join(builddir, 'etc', 'ice.config')
ice_config = os.path.abspath( ice_config )

#
# Options
#
opts = Variables()
opts.Add(BoolVariable('run', 'Execute all build artifacts', 0))
opts.Add(BoolVariable('run_java', 'Execute Java build artifacts', 0))
opts.Add(BoolVariable('run_py', 'Execute Python build artifacts', 0))
opts.Add(BoolVariable('no_java', 'Skip building all Java artifacts', 0))

# Adding to allow re-use of scons_py Ant macro
AddOption('--release',
            dest='release',
            type='string',
            nargs=1,
            action='store',
            metavar='RELEASE',
            help='Release version [debug (default) or Os]')

AddOption('--arch',
            dest='arch',
            type='string',
            nargs=1,
            action='store',
            metavar='ARCH',
            help='Architecture to build for [x86, x64, or detect (default)]')
#
# ENVIRONMENT: ===================================================
#
map = { "options" : opts,
        "JAVACFLAGS" : [],
        "ENV" : {
            "ICE_CONFIG" : ice_config,
            "PATH": os.environ["PATH"],
            "PYTHONPATH" : os.pathsep.join(pypath + [os.path.join(builddir,"lib","python")]) }}

env = Environment(**map)

# TARGETS / EXECUTION: ==========================================

#
# Helpers
#
def get_targets(env, subdir, name):

    targets = []

    # Java
    if not env["no_java"]:
        javac = env.Java(".",".")
        targets.append(javac)
        if env["run"] or env["run_java"]:
            env['ENV']['CLASSPATH'] = os.path.pathsep.join([ env['ENV']['CLASSPATH'], subdir ])
            run = env.Alias(_(["%s"%subdir, "%s.class"%name]), [], "java -ea %s " % name)
            Depends(run, javac)
            env.AlwaysBuild(run)
            targets.append(run)

    # Python
    if env["run"] or env["run_py"]:
        run = env.Alias(_(["%s"%subdir, "%s.py"%name]), [], "python " + _(["%s"%subdir, "%s.py "%name]))
        env.AlwaysBuild(run)
        targets.append(run)

    return targets

#
# Classpath
#
import glob, os
classpath = glob.glob(os.path.join(builddir,"lib","client","*.jar"))
classpath.append(os.path.join(builddir,"etc"))
env['ENV']['CLASSPATH']=os.path.pathsep.join(classpath)

#
# Targets on a per-directory basis
#
targets = []

for src_dir in glob.glob("*"):
    if os.path.isdir(src_dir):


        #
        # SConscript-based directory
        #
        sconscript = os.path.join(src_dir, "SConscript")
        if os.path.exists(sconscript):
            rv = env.SConscript(sconscript, 'env libs ice_config get_targets')
            continue

        #
        # Java
        #
        if not env["no_java"]:
            javac = env.Java(src_dir, src_dir)
            targets.append(javac)

        if env["run"] or env["run_java"]:
            java_files = glob.glob(os.path.join(src_dir, "*.java"))
            for file in java_files:
                base = os.path.basename(file)
                base = os.path.splitext(base)[0]
                # Cloning environment, so that CLASSPATH doesn't have all the subdirectories included
                clone = env.Clone()
                clone['ENV']['CLASSPATH'] = os.path.pathsep.join([ clone['ENV']['CLASSPATH'], src_dir ])
                run = clone.Alias(os.path.join(src_dir,base), [], "java -ea %s" % base)
                Depends(run, javac)
                clone.AlwaysBuild(run)
                targets.append(run)

        #
        # Python
        #
        if env["run"] or env["run_py"]:
            python_files = glob.glob(os.path.join(src_dir, "*.py"))
            for file in python_files:
                use = True
                for x in ("adminWorkflow.py", "runHellowWorld.py", "HelloWorld.py", "Edit_Descriptions.py"):
                    if file.find(x) >=0: # Workaround ticket:3243
                        use = False
                if use:
                    run = env.Alias(file, [], "python %s" % file)
                    env.AlwaysBuild(run)
                    targets.append(run)

# PREPARING SCONS EXECUTION: =================================
#
Default(targets)
Help(opts.GenerateHelpText(env))


