/**
 * Execute travis encrypt command.
 * @function task.worker.executeTravisEncrypt
 * @see http://docs.travis-ci.com/user/build-configuration/
 * @param {object} config - Task configuration.
 * @param {string} config.secretFile - Secret file.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var path = require('path'),
    debug = require('./_debug'),
    childProcess = require('child_process');

exports = module.exports = function (config, callback) {
    var secretFile = path.resolve(config.secretFile);
    exports._execute('which travis', function (err, out) {
        if (err) {
            callback(err);
            return;
        }
        if (!out) {
            callback(new Error('Command not found. Try "gem install travis"'));
            return;
        }
        var secret = require(secretFile);
        require('async').series(
            Object.keys(secret)
                .map(function (key) {
                    var value = secret[key],
                        command = [
                            'travis',
                            'encrypt',
                            [key, value].join('='),
                            '--add'
                        ].join(' ');
                    return function (callback) {
                        exports._execute(command, function (err, msg) {
                            if (!err) {
                                debug.didExecute(command);
                            }
                            callback(err);
                        });
                    }
                }),
            function (err) {
                callback(err);
            });
    });
};

exports._execute = function (command, callback) {
    childProcess.exec(command, function (err, stdOut, stdErr) {
        callback(err || stdErr || null, stdOut || null);
    });
};