import os
import sys
import subprocess as sub

# scons Jar builder isn't flexible enough to add resources from different
# directories, so first make a jar with all the class files, then create
# a copy of it and insert resource files. I have to make a copy because
# scons doesn't like to have files it generated modified. This function
# adds all files and directories under directory source[1] to the jar
# source[0], creating a new jar target[0].
def AddResources(target, source, env):
    src_jar = source[0].abspath
    tgt_jar = target[0].abspath
    Execute(Copy(tgt_jar, src_jar))
    resource_dir = source[1].srcnode().abspath
    files = ' '.join('-C %s %s' % (resource_dir, f) for f in os.listdir(resource_dir))
    cmd = 'jar uf %s %s' % (tgt_jar, files)
    return os.system(cmd)

Import('env')
java_env = env.Clone()

if not java_env.WhereIs('java') or not java_env.WhereIs('swig'):
    Return()

try:
    p = sub.Popen(['java', '-version'], stderr = sub.PIPE)
    line = p.stderr.readline().decode()
    ver_str = line.split()[-2].strip('"')
    p.wait()
except OSError:
    print >>sys.stderr, 'Error running java'
    Exit(1)

java_env['SML'] = env.File(os.path.join(env['OUT_DIR'], 'java', 'sml.jar'))
if os.name == 'nt':
    java_env['SEP'] = ';'
else:
    java_env['SEP'] = ':'

Export('java_env', 'AddResources')

for d in ['Debugger', 'DebuggerAPI', 'SMLJava']:
    SConscript(os.path.join(d, 'SConscript'))
