#!/usr/bin/env node --harmony_collections
var safeExec = require('./utils/child-process-wrapper.js').safeExec;
var fs = require('fs');
var path = require('path');

// Executes an array of commands one by one.
function executeCommands(commands, done, index) {
  index = (index == undefined ? 0 : index);
  if (index < commands.length) {
    var command = commands[index];
    var options = null;
    if (typeof command !== 'string') {
      options = command.options;
      command = command.command;
    }
    safeExec(command, options, executeCommands.bind(this, commands, done, index + 1));
  } else
    done(null);
}

var apmVendorPath = path.resolve(__dirname, '..', 'vendor', 'apm');
var apmInstallPath = path.resolve(__dirname, '..', 'apm');
if (!fs.existsSync(apmInstallPath))
  fs.mkdirSync(apmInstallPath);
if (!fs.existsSync(path.join(apmInstallPath, 'node_modules')))
  fs.mkdirSync(path.join(apmInstallPath, 'node_modules'));

var apmFlags = process.env.JANKY_SHA1 || process.argv.indexOf('--no-color') !== -1 ? '--no-color' : '';
var packagesToDedupe = ['fs-plus', 'humanize-plus', 'oniguruma', 'roaster', 'season'];
var echoNewLine = process.platform == 'win32' ? 'echo.' : 'echo';
var commands = [
  'git submodule --quiet sync',
  'git submodule --quiet update --recursive --init',
  {command: 'npm --strict-ssl=false install --quiet', options: {cwd: path.resolve(__dirname, '..', 'build'), ignoreStdout: true}},
  {command: 'npm --strict-ssl=false install --quiet', options: {cwd: apmVendorPath, ignoreStdout: true}},
  {command: 'npm --strict-ssl=false install --quiet ' + apmVendorPath, options: {cwd: apmInstallPath, ignoreStdout: true}},
  {command: 'npm --strict-ssl=false install --quiet ' + apmVendorPath, options: {ignoreStdout: true}},
  {command: 'node ../../apm/node_modules/atom-package-manager/bin/apm rebuild', options: {cwd: path.resolve('node_modules', 'atom-package-manager'), ignoreStdout: true}},
  echoNewLine,
  'node apm/node_modules/atom-package-manager/bin/apm clean ' + apmFlags,
  'node apm/node_modules/atom-package-manager/bin/apm install --quiet ' + apmFlags,
  'node apm/node_modules/atom-package-manager/bin/apm dedupe --quiet ' + apmFlags + ' ' + packagesToDedupe.join(' '),
];

process.chdir(path.dirname(__dirname));
executeCommands(commands, process.exit);
