#!/usr/bin/python


import os, sys

copy_to_template = set([])

if 'SALVUS_ROOT' in os.environ:
    # only run when building as part of hub, not local hub
    path = os.path.join(os.environ['SALVUS_ROOT'],'local_hub_template/node_modules')
    if os.path.exists(path):
        copy_to_template = set([x for x in os.listdir(path) if x.endswith('.js')])

if '--all' in sys.argv:
    all = True
    sys.argv.remove("--all")
else:
    all = False

if len(sys.argv) == 2:
    out = sys.argv[1]
else:
    out = "node_modules"

v = []
cjsx = []
copy = []
for src in os.listdir('.'):
    if src.endswith('.coffee') or src.endswith('.cjsx'):
        name = src[:src.rindex('.')]
        target = '%s/%s.js'%(out, name)
        if all or (not os.path.exists(target) or os.stat(target).st_mtime < os.stat(src).st_mtime):
            if src.endswith('.coffee'):
                v.append(src)
            elif src.endswith('.cjsx'):
                cjsx.append(src)
            if name+".js" in copy_to_template:
                copy.append(name+".js")

if cjsx:
    cmd = 'cjsx -cb -o %s %s' % (out, ' '.join(cjsx))
    print cmd
    if os.system(cmd):
        sys.exit(1)

if v:
    cmd = 'coffee -o %s -c %s'%(out, ' '.join(v))
    print cmd
    if os.system(cmd):
        sys.exit(1)
for x in copy:
    os.system("cp -v node_modules/%s local_hub_template/node_modules/&"%x)
