"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.checkOsServiceRole = void 0;
var _clientIam = require("@webiny/aws-sdk/client-iam");
var _ora = _interopRequireDefault(require("ora"));
var _chalk = require("chalk");
const NO_SUCH_ENTITY_IAM_ERROR = "NoSuchEntity";
const checkOsServiceRole = exports.checkOsServiceRole = {
  type: "hook-before-deploy",
  name: "hook-before-deploy-os-service-role",
  async hook(params, context) {
    const spinner = (0, _ora.default)();
    spinner.start(`Checking Amazon OpenSearch service role...`);
    const iam = new _clientIam.IAM();
    try {
      await iam.getRole({
        RoleName: "AWSServiceRoleForAmazonOpenSearchService"
      });
      spinner.stopAndPersist({
        symbol: (0, _chalk.green)("✔"),
        text: `Found Amazon OpenSearch service role!`
      });
      context.success(`Found Amazon OpenSearch service role!`);
    } catch (err) {
      // We've seen cases where the `iam.getRole` call fails because of an issue
      // other than not being able to retrieve the service role. Let's print
      // additional info if that's the case. Will make debugging a bit easier.
      if (err.Error?.Code !== NO_SUCH_ENTITY_IAM_ERROR) {
        spinner.fail("Tried retrieving Amazon OpenSearch service role but failed with the following error: " + err.message);
        context.debug(err);
        process.exit(1);
      }
      spinner.text = "Creating Amazon OpenSearch service role...";
      try {
        await iam.createServiceLinkedRole({
          AWSServiceName: "opensearchservice.amazonaws.com"
        });
        spinner.stop();
      } catch (err) {
        spinner.fail(err.message);
        context.debug(err);
        process.exit(1);
      }
    }
  }
};

//# sourceMappingURL=checkOsServiceRole.js.map