"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.clusterRoleTemplate = exports.roleTemplate = exports.upsertRole = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const error_1 = require("../support/error");
const retry_1 = require("../support/retry");
const labels_1 = require("./labels");
const metadata_1 = require("./metadata");
const patch_1 = require("./patch");
const request_1 = require("./request");
const resource_1 = require("./resource");
/**
 * Create or patch role or cluster role.
 *
 * @param req Kubernetes application request
 * @return Kubernetes resource spec used to create/update the resource
 */
async function upsertRole(req) {
    const slug = request_1.appName(req);
    if (req.roleSpec.kind === "ClusterRole") {
        const spec = await clusterRoleTemplate(req);
        try {
            await req.clients.rbac.readClusterRole(spec.metadata.name);
        }
        catch (e) {
            logger_1.logger.debug(`Failed to read cluster role ${slug}, creating: ${error_1.k8sErrMsg(e)}`);
            logger_1.logger.info(`Creating cluster role ${slug} using '${resource_1.logObject(spec)}'`);
            await retry_1.logRetry(() => req.clients.rbac.createClusterRole(spec), `create cluster role ${slug}`);
            return spec;
        }
        logger_1.logger.info(`Cluster role ${slug} exists, patching using '${resource_1.logObject(spec)}'`);
        await retry_1.logRetry(() => req.clients.rbac.patchClusterRole(spec.metadata.name, spec, undefined, undefined, undefined, undefined, patch_1.patchHeaders(req)), `patch cluster role ${slug}`);
        return spec;
    }
    else {
        const spec = await roleTemplate(req);
        try {
            await req.clients.rbac.readNamespacedRole(spec.metadata.name, spec.metadata.namespace);
        }
        catch (e) {
            logger_1.logger.debug(`Failed to read role ${slug}, creating: ${error_1.k8sErrMsg(e)}`);
            logger_1.logger.info(`Creating role ${slug} using '${resource_1.logObject(spec)}'`);
            await retry_1.logRetry(() => req.clients.rbac.createNamespacedRole(spec.metadata.namespace, spec), `create role ${slug}`);
            return spec;
        }
        logger_1.logger.info(`Role ${slug} exists, patching using '${resource_1.logObject(spec)}'`);
        await retry_1.logRetry(() => req.clients.rbac.patchNamespacedRole(spec.metadata.name, spec.metadata.namespace, spec, undefined, undefined, undefined, undefined, patch_1.patchHeaders(req)), `patch role ${slug}`);
        return spec;
    }
}
exports.upsertRole = upsertRole;
/**
 * Create role spec for a Kubernetes application.  The
 * `req.rbac.roleSpec` is merged into the spec created by this
 * function using `lodash.merge(default, req.rbac.roleSpec)`.
 *
 * It is possible to override the role name using the
 * [[KubernetesApplication.roleSpec]].  If you do this, make sure you
 * know what you are doing and also override it in the
 * [[KubernetesApplication.roleBindingSpec]].
 *
 * @param req application request
 * @return role resource specification
 */
async function roleTemplate(req) {
    const labels = labels_1.applicationLabels(req);
    const metadata = metadata_1.metadataTemplate({
        name: req.name,
        namespace: req.ns,
        labels,
    });
    const apiVersion = "rbac.authorization.k8s.io/v1";
    const kind = "Role";
    const r = {
        metadata,
        rules: [],
    };
    _.merge(r, req.roleSpec, { apiVersion, kind });
    r.metadata.namespace = req.ns;
    return r;
}
exports.roleTemplate = roleTemplate;
/**
 * Create role spec for a Kubernetes application.  The
 * `req.rbac.roleSpec` is merged into the spec created by this
 * function using `lodash.merge(default, req.rbac.roleSpec)`.
 *
 * It is possible to override the cluster role name using the
 * [[KubernetesApplication.roleSpec]].  If you do this, make sure you
 * know what you are doing and also override it in the
 * [[KubernetesApplication.roleBindingSpec]].
 *
 * @param req application request
 * @return role resource specification
 */
async function clusterRoleTemplate(req) {
    const labels = labels_1.applicationLabels(req);
    const metadata = metadata_1.metadataTemplate({
        name: req.name,
        labels,
    });
    const apiVersion = "rbac.authorization.k8s.io/v1";
    const kind = "ClusterRole";
    const r = {
        metadata,
        rules: [],
    };
    _.merge(r, req.roleSpec, { apiVersion, kind });
    return r;
}
exports.clusterRoleTemplate = clusterRoleTemplate;
//# sourceMappingURL=role.js.map