'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.ExecutorDockerServerless = undefined;

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _get2 = require('babel-runtime/helpers/get');

var _get3 = _interopRequireDefault(_get2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

require('source-map-support/register');

var _Executor = require('../agent/Executor');

var _ExecutorDocker2 = require('./ExecutorDocker');

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _AgentUtils = require('../agent/AgentUtils');

var _KmsUtils = require('../KmsUtils');

var _KmsUtils2 = _interopRequireDefault(_KmsUtils);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Sample .githubTaskManager.json task config
 *
 * see: https://github.com/zotoio/github-task-manager/wiki/Structure-of-.githubTaskManager.json
 *
{
  "pull_request": {
    "agentGroup": "K8S",
    "tasks": [
      {
        "executor": "DockerServerless",
        "context": "Deploy Lambda",
        "options": {
           "env": {"BUILD_TYPE": "nodejs"}
        }
      }
    ]
  }
}

 *
 */

var ExecutorDockerServerless = exports.ExecutorDockerServerless = function (_ExecutorDocker) {
    (0, _inherits3.default)(ExecutorDockerServerless, _ExecutorDocker);

    function ExecutorDockerServerless(eventData, log) {
        (0, _classCallCheck3.default)(this, ExecutorDockerServerless);

        var _this = (0, _possibleConstructorReturn3.default)(this, (ExecutorDockerServerless.__proto__ || (0, _getPrototypeOf2.default)(ExecutorDockerServerless)).call(this, eventData, log));

        _this.eventData = eventData;
        _this.log = log;
        _this._packagesToDeploy = _this.identifyChangedPackages();
        _this.pushBranch = _this.pushBranchName();
        return _this;
    }

    (0, _createClass3.default)(ExecutorDockerServerless, [{
        key: 'executeTask',
        value: function () {
            var _ref = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(task) {
                return _regenerator2.default.wrap(function _callee$(_context) {
                    while (1) {
                        switch (_context.prev = _context.next) {
                            case 0:
                                _context.next = 2;
                                return this.mergeTaskOptions(task);

                            case 2:
                                task.options = _context.sent;
                                return _context.abrupt('return', (0, _get3.default)(ExecutorDockerServerless.prototype.__proto__ || (0, _getPrototypeOf2.default)(ExecutorDockerServerless.prototype), 'executeTask', this).call(this, task));

                            case 4:
                            case 'end':
                                return _context.stop();
                        }
                    }
                }, _callee, this);
            }));

            function executeTask(_x) {
                return _ref.apply(this, arguments);
            }

            return executeTask;
        }()
    }, {
        key: 'pushBranchName',
        value: function pushBranchName() {
            var refParts = this.eventData.ref ? this.eventData.ref.split('/') : [];
            var branchName = refParts.length > 0 ? refParts[refParts.length - 1].replace(/[^A-Za-z0-9\-+_]/g, '-') : null;
            this.log.info('pushBranchName: ' + branchName);
            return branchName;
        }
    }, {
        key: 'identifyChangedPackages',
        value: function identifyChangedPackages() {
            var packages = [];
            this.eventData.commits.forEach(function (commit) {
                ['added', 'removed', 'modified'].forEach(function (changeType) {
                    commit[changeType].forEach(function (path) {
                        if (path.startsWith('packages/')) {
                            var pack = path.split('/')[1];
                            if (!packages.includes(pack)) {
                                packages.push(pack);
                            }
                        }
                    });
                });
            });
            this.log.info('serverless packages to deploy ' + packages);

            return packages;
        }
    }, {
        key: 'slsStage',
        value: function slsStage() {
            var stage = process.env.GTM_SLS_EXECUTOR_AWS_STAGE || this.eventData.pushForPullRequest ? 'test' : 'dev';
            this.log.info('stage: ' + stage);
            return stage;
        }
    }, {
        key: 'mergeTaskOptions',
        value: function () {
            var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee2(task) {
                var options;
                return _regenerator2.default.wrap(function _callee2$(_context2) {
                    while (1) {
                        switch (_context2.prev = _context2.next) {
                            case 0:
                                options = {
                                    image: process.env.GTM_DOCKER_DEFAULT_WORKER_IMAGE || 'zotoio/gtm-worker:latest',
                                    command: '/usr/workspace/serverless-mono-deploy.sh',
                                    env: {
                                        GIT_CLONE: '##GH_CLONE_URL##',
                                        GIT_PR_ID: '##GHPRNUM##',
                                        GIT_PR_BRANCHNAME: '##GH_PR_BRANCHNAME##',
                                        GIT_PUSH_BRANCHNAME: this.pushBranch,
                                        GIT_URL: '##GIT_URL##',
                                        GIT_COMMIT: '##GIT_COMMIT##',
                                        GTM_EVENT_ID: this.eventData.ghEventId,
                                        SLS_AFFECTED_PACKAGES: this.packagesToDeploy.join(','),
                                        IAM_ENABLED: process.env.IAM_ENABLED,
                                        S3_DEPENDENCY_BUCKET: '##GTM_S3_DEPENDENCY_BUCKET##',
                                        AWS_S3_PROXY: '##GTM_AWS_S3_PROXY##',
                                        SLS_AWS_STAGE: this.slsStage(),
                                        SLS_AWS_REGION: process.env.GTM_SLS_EXECUTOR_AWS_REGION || 'ap-southeast-2',
                                        SLS_AWS_EXECUTION_ROLE: process.env.GTM_SLS_EXECUTOR_AWS_EXECUTION_ROLE,
                                        SLS_DEPLOY_MODE: process.env.GTM_SLS_EXECUTOR_DEPLOY_MODE || 'parallel'
                                    },
                                    validator: {
                                        type: 'outputRegex',
                                        regex: '.*ALL DEPLOYS SUCCESSFUL.*'
                                    }
                                };

                                if (process.env.IAM_ENABLED) {
                                    _context2.next = 9;
                                    break;
                                }

                                _context2.next = 4;
                                return _KmsUtils2.default.getDecrypted(process.env.GTM_CRYPT_AGENT_AWS_ACCESS_KEY_ID);

                            case 4:
                                options.env['GTM_AWS_ACCESS_KEY_ID'] = _context2.sent;
                                _context2.next = 7;
                                return _KmsUtils2.default.getDecrypted(process.env.GTM_CRYPT_AGENT_AWS_SECRET_ACCESS_KEY);

                            case 7:
                                options.env['GTM_AWS_SECRET_ACCESS_KEY'] = _context2.sent;

                                options.env['GTM_AWS_REGION'] = process.env.GTM_AWS_REGION;

                            case 9:

                                // options defined above can be overidden by options in .githubTaskManager.json
                                task.options = _lodash2.default.merge(options, task.options);

                                _context2.t0 = _AgentUtils.AgentUtils;
                                _context2.t1 = _AgentUtils.AgentUtils;
                                _context2.next = 14;
                                return _AgentUtils.AgentUtils.createBasicTemplate(this.eventData, {}, this.log);

                            case 14:
                                _context2.t2 = _context2.sent;
                                _context2.t3 = task.options;
                                _context2.t4 = this.log;
                                _context2.t5 = _context2.t1.templateReplace.call(_context2.t1, _context2.t2, _context2.t3, _context2.t4);
                                task.options = _context2.t0.applyTransforms.call(_context2.t0, _context2.t5);


                                // add token into clone url
                                task.options.env.GIT_CLONE = task.options.env.GIT_CLONE.replace('https://', 'https://' + task.options.env.GTM_CRYPT_GITHUB_TOKEN + '@');

                                return _context2.abrupt('return', task.options);

                            case 21:
                            case 'end':
                                return _context2.stop();
                        }
                    }
                }, _callee2, this);
            }));

            function mergeTaskOptions(_x2) {
                return _ref2.apply(this, arguments);
            }

            return mergeTaskOptions;
        }()
    }, {
        key: 'packagesToDeploy',
        get: function get() {
            return this._packagesToDeploy;
        }
    }]);
    return ExecutorDockerServerless;
}(_ExecutorDocker2.ExecutorDocker);

_Executor.Executor.register('DockerServerless', ExecutorDockerServerless);