"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.namespaceTemplate = exports.upsertNamespace = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
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 resource_1 = require("./resource");
/**
 * Create or update a namespace.
 *
 * @param req Kuberenetes application request
 * @return Kubernetes resource spec used to create/patch the resource
 */
async function upsertNamespace(req) {
    const slug = req.ns;
    const spec = await namespaceTemplate(req);
    try {
        await req.clients.core.readNamespace(spec.metadata.name);
        logger_1.logger.debug(`Namespace ${slug} exists`);
    }
    catch (e) {
        logger_1.logger.debug(`Failed to get namespace ${slug}, creating: ${error_1.k8sErrMsg(e)}`);
        logger_1.logger.info(`Creating namespace ${slug} using '${resource_1.logObject(spec)}'`);
        await retry_1.logRetry(() => req.clients.core.createNamespace(spec), `create namespace ${slug}`);
        return spec;
    }
    logger_1.logger.info(`Namespace ${slug} exists, patching using '${resource_1.logObject(spec)}'`);
    try {
        await retry_1.logRetry(() => req.clients.core.patchNamespace(spec.metadata.name, spec, undefined, undefined, undefined, undefined, patch_1.patchHeaders(req)), `patch namespace ${slug}`);
    }
    catch (e) {
        logger_1.logger.warn(`Failed to patch existing namespace ${slug}, ignoring: ${error_1.k8sErrMsg(e)}`);
    }
    return spec;
}
exports.upsertNamespace = upsertNamespace;
/**
 * Create namespace resource.
 *
 * @param req Kubernetes application
 * @return Kubernetes namespace resource
 */
async function namespaceTemplate(req) {
    const allLabels = labels_1.applicationLabels(req);
    const retain = ["atomist.com/workspaceId", "app.kubernetes.io/managed-by"];
    const labels = Object.assign({}, ...Object.keys(allLabels).filter(k => retain.includes(k)).map(k => ({ [k]: allLabels[k] })));
    const metadata = metadata_1.metadataTemplate({ labels, name: req.ns });
    const ns = {
        apiVersion: "v1",
        kind: "Namespace",
        metadata,
    };
    return ns;
}
exports.namespaceTemplate = namespaceTemplate;
//# sourceMappingURL=namespace.js.map