#!/usr/bin/python
#
# Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

"""Based on experimental/apps/total/endart/bin/endart.
TODO(jacobr): there has to be a better way to integrate this with the build.
"""

import fnmatch
import glob
import os
import subprocess
import sys

# Add the tools directory so we can find utils.py.
sys.path.append(os.path.abspath(os.path.join(
    os.path.dirname(__file__),
    "../../../../tools")))

import utils


def flatten(iterable):
  it = iter(iterable)
  for e in it:
    if isinstance(e, (list, tuple)):
      for f in flatten(e):
        yield f
    else:
        yield e

def thisJar(file):
  root = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..'))
  return [os.path.join(root, file)]

def allJars(directory):
  matches = []
  root = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '..'))
  for path, dirs, files in os.walk(os.path.join(root, directory)):
    for file in fnmatch.filter(files, '*.jar'):
      matches.append(os.path.normpath(os.path.join(root, path, file)))
  return matches

def classpath(libs):
  return ':'.join(flatten(libs))

def main():
  buildRoot = utils.GetBuildRoot(utils.GuessOS(), "debug", "dartc")

  cp = classpath([
    thisJar(os.path.join('../../', buildRoot, 'dartserver/dartserver.jar')),
    thisJar(os.path.join('../../', buildRoot, 'dartserver/libutil.jar')),
    allJars(os.path.join('../../', buildRoot, 'compiler/lib')),
    allJars('../../../third_party/jetty/7.4.4.v20110707'),
  ])
  root = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),
                                      '../../../../client'))
  subprocess.call([ 'java', '-classpath', cp,
                    'com.google.appstack.tools.dartserver.DartServer'] +
                        [root] + sys.argv[1:])

if __name__ == '__main__':
  main()
