"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUserArn = exports.initIamClient = void 0;
const client_iam_1 = require("@aws-sdk/client-iam");
const logger_1 = require("../../../logger");
const regex_1 = require("../../../util/regex");
let iam;
function initIamClient(region, credentials) {
    if (!iam) {
        iam = new client_iam_1.IAMClient({
            region,
            credentials,
        });
    }
}
exports.initIamClient = initIamClient;
const userRe = (0, regex_1.regEx)(/User:\s*(?<arn>[^ ]+).*/);
/**
 * This method will throw an exception only in case we have no connection
 * 1) there is a connection and we return user.arn.
 * 2) there is a connection but no permission for the current user, we still get his user arn in the error message
 * 3) there is a problem in the connection to the aws api, then throw an error with the err
 */
async function getUserArn() {
    const cmd = new client_iam_1.GetUserCommand({});
    let res;
    try {
        const userRes = await iam.send(cmd);
        res = userRes?.User?.Arn;
    }
    catch (err) {
        const match = userRe.exec(err.message);
        if (match) {
            logger_1.logger.warn('It is recommended to add "IAMReadOnlyAccess" policy to this IAM user');
            res = match.groups?.arn;
        }
        if (!res) {
            logger_1.logger.warn('Failed to get IAM user info, Make sure your user has "IAMReadOnlyAccess" policy');
            throw err;
        }
    }
    return res ?? '';
}
exports.getUserArn = getUserArn;
//# sourceMappingURL=iam-client.js.map