#!/usr/bin/python

from os import chdir, environ as env, path, popen, system, uname

# We are using this old version since terminal resize doesn't work in 0.10.2!
VERSION="0.8.22"

import os, sys

if 'MAKE' in env:
    # Just in case somebody has "make -j24" for sage, which breaks the build of node.js.
    del os.environ['MAKE']

P = path.join(env['HOME'], '.sagemathcloud')
env['PATH'] = "%s:%s/node_modules/.bin/:%s/data/local/bin:%s"%(P, P, P, env['PATH'])

chdir(P)

if os.path.exists('installed'):
    os.unlink('installed')

install_node = True
try:
    node_version = popen('node --version').read()[1:]
    # output looks like this: '0.10.2\n'
    if node_version == VERSION:
        install_node = False
except:
    pass


if install_node:
    version = VERSION

    u = uname()
    if u[-1] == 'x86_64':
        arch = "x64"
    else:
        arch = "x86"
    uname = u[0].lower()
    node_folder = "node-v%s-%s-%s"%(version, uname, arch)
    tarball = node_folder + '.tar.gz'

    # For example:
    #   wget http://nodejs.org/dist/v0.10.2/node-v0.10.2-linux-x64.tar.gz
    cmd = "rm -f node-v%s* && wget http://nodejs.org/dist/v%s/%s && mkdir -p data/local && cd data/local && tar zxvf ../../%s && mv '%s'/* . && rm -rf '%s'"%(
        version, version, tarball, tarball, node_folder, node_folder)
    if os.system(cmd):
        print "FAILED to download and install node..."
        sys.exit(1)
    os.unlink(tarball)

# Install all the modules we need for the local hub.
# TODO -- under what conditions should we do this?
if system("./install_npm_modules"):
    print "Failed to install all modules"
    sys.exit(1)

# Build coffeescript to javascript
system("./make_coffee")

open('installed', 'w')

# First build leaves an empty directory laying around; delete it if empty.
try:
    os.rmdir('tmp')
except:
    pass
