"use strict";
var _npm_1 = require('./@npm');
var task_utils_1 = require("../task.utils");
var debug = require('debug')('cb:@bg');
var merge = require('../../lodash.custom').merge;
module.exports = function (task, trigger) {
    // todo teardown multiple background emitters on ExitSignal
    //
    var emitter;
    trigger.config.signalObserver.subscribe(function (signal) {
        if (emitter) {
            _npm_1.teardown(emitter, task);
        }
    });
    return function (opts, ctx, done) {
        var args = _npm_1.getArgs(task.command);
        var npmEnv = _npm_1.getEnv(process, trigger.config);
        var cbEnv = task_utils_1.getCBEnv(trigger);
        var env = merge({}, process.env, npmEnv, cbEnv, task.env, trigger.config.env);
        var stdio = _npm_1.getStdio(trigger);
        debug("running %s", args.cmd);
        emitter = _npm_1.runCommand(args.cmd, {
            cwd: trigger.config.cwd,
            env: env,
            stdio: stdio
        });
        emitter.on('close', function (code) {
            _npm_1.teardown(emitter, task);
        }).on('error', function (err) {
            done(err);
        });
        done(null, function tearDownBgAdaptor() {
            _npm_1.teardown(emitter, task);
        });
    };
};
//# sourceMappingURL=@bg.js.map