ChildProcess = require 'child_process'

# Spawn a command and invoke the callback when it completes with an error
# and the output from standard out.
#
# * `command`    The underlying OS command {String} to execute.
# * `args` (optional) The {Array} with arguments to be passed to command.
# * `callback` (optional) The {Function} to call after the command has run. It will be invoked with arguments:
#   * `error` (optional) An {Error} object returned by the command, `null` if no error was thrown.
#     * `code` Error code returned by the command.
#     * `stdout`  The {String} output text generated by the command.
#   * `stdout`  The {String} output text generated by the command.
#
# Returns `undefined`.
exports.spawn = (command, args, callback) ->
  stdout = ''

  try
    spawnedProcess = ChildProcess.spawn(command, args)
  catch error
    # Spawn can throw an error
    process.nextTick -> callback?(error, stdout)
    return

  spawnedProcess.stdout.on 'data', (data) -> stdout += data

  error = null
  spawnedProcess.on 'error', (processError) -> error ?= processError
  spawnedProcess.on 'close', (code, signal) ->
    error ?= new Error("Command failed: #{signal ? code}") if code isnt 0
    error?.code ?= code
    error?.stdout ?= stdout
    callback?(error, stdout)
  # This is necessary if using Powershell 2 on Windows 7 to get the events to raise
  # http://stackoverflow.com/questions/9155289/calling-powershell-from-nodejs
  spawnedProcess.stdin.end()
