"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _gitconfig() {
  const data = _interopRequireDefault(require("@teambit/gitconfig"));

  _gitconfig = function () {
    return data;
  };

  return data;
}

function _yn() {
  const data = _interopRequireDefault(require("yn"));

  _yn = function () {
    return data;
  };

  return data;
}

function globalConfig() {
  const data = _interopRequireWildcard(require("../../api/consumer/lib/global-config"));

  globalConfig = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _logger() {
  const data = _interopRequireDefault(require("../../logger/logger"));

  _logger = function () {
    return data;
  };

  return data;
}

/**
 * Add more keys to the context which will be passed to hooks
 * @param {Object} context
 */
function enrichContextFromGlobal(context = {}) {
  _logger().default.debug('enrich context from global config');

  const getContextToEnrich = () => {
    // $FlowFixMe
    if (!enrichContextFromGlobal.context) {
      const username = globalConfig().getSync(_constants().CFG_USER_NAME_KEY);
      const email = globalConfig().getSync(_constants().CFG_USER_EMAIL_KEY);
      const sshKeyFile = globalConfig().getSync(_constants().CFG_SSH_KEY_FILE_KEY);
      const token = globalConfig().getSync(_constants().CFG_USER_TOKEN_KEY);
      const pubSshKeyFile = sshKeyFile ? `${sshKeyFile}.pub` : undefined;

      const pubSshKey = _getSshPubKey(pubSshKeyFile);

      const repo = (0, _yn().default)(globalConfig().getSync(_constants().CFG_REPOSITORY_REPORTING_KEY), {
        default: true
      }) ? _gitconfig().default.getUrl() : undefined;
      enrichContextFromGlobal.context = {
        username,
        email,
        pubSshKey,
        token,
        repo
      };
    }

    return enrichContextFromGlobal.context;
  };

  const contextToEnrich = getContextToEnrich();
  Object.assign(context, contextToEnrich);
}

function _getSshPubKey(pubSshKeyFile = `${_constants().DEFAULT_SSH_KEY_FILE}.pub`) {
  _logger().default.debug(`reading ssh public key from ${pubSshKeyFile}`);

  if (!_fsExtra().default.pathExistsSync(pubSshKeyFile)) {
    return null;
  }

  const buf = _fsExtra().default.readFileSync(pubSshKeyFile);

  return buf.toString();
}