#!/usr/bin/env node

var spawn = require('cross-spawn-async')
var findNearestFile = require('find-nearest-file')
var path = require('path')
var userHome = require('user-home')
var pathExists = require('path-exists')

// .zuulrc logic from https://github.com/defunctzombie/zuul/blob/a0de46a5906c84b19f655c487f7c8debe938984d/bin/zuul#L384
var zuulrcPath = findNearestFile('.zuulrc') || path.join(userHome, '.zuulrc')
var hasSauceLabEnvVars = process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY
var runSauceLabs = hasSauceLabEnvVars || pathExists.sync(zuulrcPath)

npmRun('test-node', function (code) {
  if (code === 0) {
    npmRun('test-browser-headless', function (code) {
      if (code === 0 && runSauceLabs) {
        npmRun('test-browser', function (code) {
          process.exit(code)
        })
      } else {
        process.exit(code)
      }
    })
  } else {
    process.exit(code)
  }
})

function npmRun (scriptName, onClose) {
  spawn('npm', ['run', scriptName], { stdio: 'inherit' }).on('close', onClose)
}

@@ -604,30 +604,8 @@
 ) %7B%0A
-  if (code === 0) %7B%0A  
   np
@@ -660,28 +660,12 @@
     
-  
 if (
-code === 0 && 
 runS
@@ -672,26 +672,24 @@
 auceLabs) %7B%0A
-  
       npmRun
@@ -708,36 +708,8 @@
 er',
- function (code) %7B%0A         
  pro
@@ -721,28 +721,10 @@
 exit
-(code
 )%0A
-        %7D)%0A  
     
@@ -738,18 +738,16 @@
 %7B%0A      
- 
- 
 process.
@@ -765,56 +765,14 @@
     
-  %7D%0A    %7D)%0A  %7D else %7B%0A    process.exit(code)%0A  %7D
+%7D%0A  %7D)
 %0A%7D)%0A
@@ -882,19 +882,119 @@
 close', 
-onClose
+function (code) %7B%0A    if (code === 0) %7B%0A      onClose(code)%0A    %7D else %7B%0A      process.exit(code)%0A    %7D%0A  %7D
 )%0A%7D%0A

move process.exit logic into npmRun helper