<commit_before>'use strict';

var fs = require("fs");
var async = require("async");
var deployer = require("soajs.core.drivers");

var colls = {
    env: 'environment',
    git: 'git_accounts',
    services: 'services',
    daemons: 'daemons',
    staticContent: 'staticContent'
};

function checkIfError(soajs, res, data, cb) {
    if (data.error) {
        if (data.error.source === 'driver') {
            soajs.log.error(data.error);
            return res.jsonp(soajs.buildResponse({"code": data.error.code, "msg": data.error.msg}));
        }

        if (typeof (data.error) === 'object' && (data.error.message || data.error.msg)) {
            soajs.log.error(data.error);
        }

        return res.jsonp(soajs.buildResponse({"code": data.code, "msg": data.config.errors[data.code]}));
    } else {
        if (cb) return cb();
    }
}

function getEnvironment(soajs, code, cb) {
    var opts = {
        collection: colls.env,
        conditions: { code: code.toUpperCase() }
    };

    BL.model.findEntry(soajs, opts, cb);
}

function getGitRecord(soajs, repo, cb) {
    var opts = {
        collection: colls.git,
        conditions: { 'repos.name': repo },
        fields: {
            provider: 1,
            domain: 1,
            token: 1,
            'repos.$': 1
        }
    };

    BL.model.findEntry(soajs, opts, cb);
}

function buildDeployerOptions(envRecord, soajs) {
    var options = {};
    var envDeployer = envRecord.deployer;

    if (!envDeployer) return null;
    if (Object.keys(envDeployer).length === 0) return null;
    if (!envDeployer.type || !envDeployer.selected) return null;
    if (envDeployer.type === 'manual') return null;

    var selected = envDeployer.selected.split('.');

    options.strategy = selected[1];
    options.driver = selected[1] + '.' + selected[2];
    options.env = envRecord.code.toLowerCase();

    for (var i = 0; i < selected.length; i++) {
        envDeployer = envDeployer[selected[i]];
    }

    options.deployerConfig = envDeployer;
    options.soajs = { registry: soajs.registry };
    options.model = BL.model;

    //temporary///////
    if (options.strategy === 'docker') options.strategy = 'swarm';
    //////////////////

    return options;
}

function deployServiceOrDaemon(config, soajs, registry, res) {
    var context = {
        name: '',
        origin: ''
    };

    function getEnvInfo(cb) {
        getEnvironment(soajs, soajs.inputmaskData.env, function (error, envRecord) {
            checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () {
                checkIfError(soajs, res, {config: config, error: envRecord.deployer.type === 'manual', code: 618}, function () {
                    context.envRecord = envRecord;
                    return cb();
                });
            });
        });
    }

    function getDashboardConnection(cb) {
        getDashDbInfo(soajs, function (error, data) {
            checkIfError(soajs, res, {config: config, error: error, code: 600}, function () {
                context.mongoDbs = data.mongoDbs;
                context.mongoCred = data.mongoCred;
                context.clusterInfo = data.clusterInfo;
                context.dbConfig = data.dbConfig;

                context.origin = context.name = soajs.inputmaskData.name;
                if (soajs.inputmaskData.type === 'service' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) {
                    context.name = soajs.inputmaskData.contentConfig.service.gcName;
                    context.origin = "gcs";
                }
                return cb();
            });
        });
    }

    function getGitInfo(cb) {
        getGitRecord(soajs, soajs.inputmaskData.gitSource.owner + '/' + soajs.inputmaskData.gitSource.repo, function (error, accountRecord) {
            checkIfError(soajs, res, {config: config, error: error || !accountRecord, code: 600}, function () {
                context.accountRecord = accountRecord;

                context.accountRecord.providerName = context.accountRecord.provider;

                if (context.accountRecord.providerName.indexOf('_') !== -1) {
                    context.accountRecord.providerName = context.accountRecord.providerName.split('_')[0];
                }

                return cb();
            });
        });
    }

    function getServiceDaemonInfo(cb) {
        var opts = {
            collection: ((soajs.inputmaskData.type === 'service') ? colls.services : colls.daemons ),
            conditions: {
                name: context.name
            }
        };
        BL.model.findEntry(soajs, opts, function (error, dbRecord) {
            checkIfError(soajs, res, {config: config, error: error || !dbRecord, code: 600}, function () {
                registry.loadByEnv({ envCode: soajs.inputmaskData.env.toLowerCase() }, function (error, registry) {
                    checkIfError(soajs, res, {config: config, error: error, code: 446}, function () {
                        context.dbRecord = dbRecord;
                        context.dbRecord.maintenancePort = context.dbRecord.port + registry.serviceConfig.ports.maintenanceInc;
                        return cb();
                    });
                });
            });
        });
    }

    function constructDeployerParams(cb) {
    	var serviceName = soajs.inputmaskData.env.toLowerCase() + "-" + context.name;
    	if(context.name !== 'controller'){
    		serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : "";
	    }
        var serviceParams = {
            "env": soajs.inputmaskData.env.toLowerCase(),
            "name": cleanLabel(serviceName),
            "image": soajs.inputmaskData.deployConfig.imagePrefix + "/soajs",
            "variables": [
                "NODE_ENV=production",

                "SOAJS_ENV=" + soajs.inputmaskData.env.toLowerCase(),
                "SOAJS_PROFILE=" + context.envRecord.profile,
                "SOAJS_SRV_AUTOREGISTERHOST=true",

                "SOAJS_MONGO_NB=" + context.mongoDbs.length,

                "SOAJS_GIT_OWNER=" + soajs.inputmaskData.gitSource.owner,
                "SOAJS_GIT_REPO=" + soajs.inputmaskData.gitSource.repo,
                "SOAJS_GIT_BRANCH=" + soajs.inputmaskData.gitSource.branch,
                "SOAJS_GIT_COMMIT=" + soajs.inputmaskData.gitSource.commit
            ],
            "labels": { //very useful when filtering
                "soajs.content": "true",

                "soajs.env.code": soajs.inputmaskData.env.toLowerCase(),

                "soajs.service.name": cleanLabel(context.dbRecord.name),
                "soajs.service.group": ((context.dbRecord.group) ? cleanLabel(context.dbRecord.group) : ''),
                "soajs.service.type": soajs.inputmaskData.type,
                "soajs.service.version": "" + soajs.inputmaskData.version,
                "soajs.service.label": cleanLabel(serviceName)
            },
            "cmd": [
                'bash',
                '-c',
                './soajsDeployer.sh -T service -X deploy -g ' + context.accountRecord.providerName + ' -G ' + context.accountRecord.domain
            ],
            "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit,
            "replication": {
                "mode": soajs.inputmaskData.deployConfig.replication.mode,
                "replicas": ((soajs.inputmaskData.deployConfig.replication.mode === 'replicated') ? soajs.inputmaskData.deployConfig.replication.replicas : null)
            },
            "version": soajs.inputmaskData.version || "",
            "containerDir": config.imagesDir,
            "restartPolicy": {
                "condition": "any", //TODO: make dynamic
                "maxAttempts": 5 //TODO: make dynamic
            },
            "network": config.network,
            "ports": [<commit_msg>Removed cleanLabel() from soajs.service.name in serviceParams<commit_after>'use strict';

var fs = require("fs");
var async = require("async");
var deployer = require("soajs.core.drivers");

var colls = {
    env: 'environment',
    git: 'git_accounts',
    services: 'services',
    daemons: 'daemons',
    staticContent: 'staticContent'
};

function checkIfError(soajs, res, data, cb) {
    if (data.error) {
        if (data.error.source === 'driver') {
            soajs.log.error(data.error);
            return res.jsonp(soajs.buildResponse({"code": data.error.code, "msg": data.error.msg}));
        }

        if (typeof (data.error) === 'object' && (data.error.message || data.error.msg)) {
            soajs.log.error(data.error);
        }

        return res.jsonp(soajs.buildResponse({"code": data.code, "msg": data.config.errors[data.code]}));
    } else {
        if (cb) return cb();
    }
}

function getEnvironment(soajs, code, cb) {
    var opts = {
        collection: colls.env,
        conditions: { code: code.toUpperCase() }
    };

    BL.model.findEntry(soajs, opts, cb);
}

function getGitRecord(soajs, repo, cb) {
    var opts = {
        collection: colls.git,
        conditions: { 'repos.name': repo },
        fields: {
            provider: 1,
            domain: 1,
            token: 1,
            'repos.$': 1
        }
    };

    BL.model.findEntry(soajs, opts, cb);
}

function buildDeployerOptions(envRecord, soajs) {
    var options = {};
    var envDeployer = envRecord.deployer;

    if (!envDeployer) return null;
    if (Object.keys(envDeployer).length === 0) return null;
    if (!envDeployer.type || !envDeployer.selected) return null;
    if (envDeployer.type === 'manual') return null;

    var selected = envDeployer.selected.split('.');

    options.strategy = selected[1];
    options.driver = selected[1] + '.' + selected[2];
    options.env = envRecord.code.toLowerCase();

    for (var i = 0; i < selected.length; i++) {
        envDeployer = envDeployer[selected[i]];
    }

    options.deployerConfig = envDeployer;
    options.soajs = { registry: soajs.registry };
    options.model = BL.model;

    //temporary///////
    if (options.strategy === 'docker') options.strategy = 'swarm';
    //////////////////

    return options;
}

function deployServiceOrDaemon(config, soajs, registry, res) {
    var context = {
        name: '',
        origin: ''
    };

    function getEnvInfo(cb) {
        getEnvironment(soajs, soajs.inputmaskData.env, function (error, envRecord) {
            checkIfError(soajs, res, {config: config, error: error || !envRecord, code: 600}, function () {
                checkIfError(soajs, res, {config: config, error: envRecord.deployer.type === 'manual', code: 618}, function () {
                    context.envRecord = envRecord;
                    return cb();
                });
            });
        });
    }

    function getDashboardConnection(cb) {
        getDashDbInfo(soajs, function (error, data) {
            checkIfError(soajs, res, {config: config, error: error, code: 600}, function () {
                context.mongoDbs = data.mongoDbs;
                context.mongoCred = data.mongoCred;
                context.clusterInfo = data.clusterInfo;
                context.dbConfig = data.dbConfig;

                context.origin = context.name = soajs.inputmaskData.name;
                if (soajs.inputmaskData.type === 'service' && soajs.inputmaskData.contentConfig && soajs.inputmaskData.contentConfig.service && soajs.inputmaskData.contentConfig.service.gc) {
                    context.name = soajs.inputmaskData.contentConfig.service.gcName;
                    context.origin = "gcs";
                }
                return cb();
            });
        });
    }

    function getGitInfo(cb) {
        getGitRecord(soajs, soajs.inputmaskData.gitSource.owner + '/' + soajs.inputmaskData.gitSource.repo, function (error, accountRecord) {
            checkIfError(soajs, res, {config: config, error: error || !accountRecord, code: 600}, function () {
                context.accountRecord = accountRecord;

                context.accountRecord.providerName = context.accountRecord.provider;

                if (context.accountRecord.providerName.indexOf('_') !== -1) {
                    context.accountRecord.providerName = context.accountRecord.providerName.split('_')[0];
                }

                return cb();
            });
        });
    }

    function getServiceDaemonInfo(cb) {
        var opts = {
            collection: ((soajs.inputmaskData.type === 'service') ? colls.services : colls.daemons ),
            conditions: {
                name: context.name
            }
        };
        BL.model.findEntry(soajs, opts, function (error, dbRecord) {
            checkIfError(soajs, res, {config: config, error: error || !dbRecord, code: 600}, function () {
                registry.loadByEnv({ envCode: soajs.inputmaskData.env.toLowerCase() }, function (error, registry) {
                    checkIfError(soajs, res, {config: config, error: error, code: 446}, function () {
                        context.dbRecord = dbRecord;
                        context.dbRecord.maintenancePort = context.dbRecord.port + registry.serviceConfig.ports.maintenanceInc;
                        return cb();
                    });
                });
            });
        });
    }

    function constructDeployerParams(cb) {
    	var serviceName = soajs.inputmaskData.env.toLowerCase() + "-" + context.name;
    	if(context.name !== 'controller'){
    		serviceName += (soajs.inputmaskData.version) ? "-v" + soajs.inputmaskData.version : "";
	    }
        var serviceParams = {
            "env": soajs.inputmaskData.env.toLowerCase(),
            "name": cleanLabel(serviceName),
            "image": soajs.inputmaskData.deployConfig.imagePrefix + "/soajs",
            "variables": [
                "NODE_ENV=production",

                "SOAJS_ENV=" + soajs.inputmaskData.env.toLowerCase(),
                "SOAJS_PROFILE=" + context.envRecord.profile,
                "SOAJS_SRV_AUTOREGISTERHOST=true",

                "SOAJS_MONGO_NB=" + context.mongoDbs.length,

                "SOAJS_GIT_OWNER=" + soajs.inputmaskData.gitSource.owner,
                "SOAJS_GIT_REPO=" + soajs.inputmaskData.gitSource.repo,
                "SOAJS_GIT_BRANCH=" + soajs.inputmaskData.gitSource.branch,
                "SOAJS_GIT_COMMIT=" + soajs.inputmaskData.gitSource.commit
            ],
            "labels": { //very useful when filtering
                "soajs.content": "true",

                "soajs.env.code": soajs.inputmaskData.env.toLowerCase(),

                // "soajs.service.name": cleanLabel(context.dbRecord.name),
                "soajs.service.name": context.dbRecord.name,
                "soajs.service.group": ((context.dbRecord.group) ? cleanLabel(context.dbRecord.group) : ''),
                "soajs.service.type": soajs.inputmaskData.type,
                "soajs.service.version": "" + soajs.inputmaskData.version,
                "soajs.service.label": cleanLabel(serviceName)
            },
            "cmd": [
                'bash',
                '-c',
                './soajsDeployer.sh -T service -X deploy -g ' + context.accountRecord.providerName + ' -G ' + context.accountRecord.domain
            ],
            "memoryLimit": soajs.inputmaskData.deployConfig.memoryLimit,
            "replication": {
                "mode": soajs.inputmaskData.deployConfig.replication.mode,
                "replicas": ((soajs.inputmaskData.deployConfig.replication.mode === 'replicated') ? soajs.inputmaskData.deployConfig.replication.replicas : null)
            },
            "version": soajs.inputmaskData.version || "",
            "containerDir": config.imagesDir,
            "restartPolicy": {
                "condition": "any", //TODO: make dynamic
                "maxAttempts": 5 //TODO: make dynamic
            },
            "network": config.network,
            "ports": [
{'fraction_non_alphanumeric': 0.13705139427285232, 'fraction_numerical': 0.003751406777541578, 'mean_word_length': 2.055396370582617, 'pattern_counts': {'":': 57, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6760247', 'n_tokens_mistral': 4932, 'n_tokens_neox': 4709, 'n_words': 823}