"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.destination = exports.llog = exports.deployAppId = exports.deployApplication = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const application_1 = require("../kubernetes/application");
const request_1 = require("../kubernetes/request");
const application_2 = require("../sync/application");
const cluster_1 = require("./cluster");
const data_1 = require("./data");
const externalUrls_1 = require("./externalUrls");
/**
 * Given an SdmGoalEvent with the appropriate Kubernetes application
 * data, deploy an application to a Kubernetes cluster.
 *
 * @param goalEvent The Kubernetes deployment goal
 * @param context A standard handler context available from goal executions
 *                or event handlers
 * @param log     SDM goal progress log
 * @return Goal success or failure, with endpoint URL(s) on success if
 *         ingress properties are set
 */
async function deployApplication(goalEvent, context, log) {
    let appId = deployAppId(goalEvent, context);
    llog(`Processing ${appId}`, logger_1.logger.debug, log);
    let dest = destination(goalEvent);
    let app;
    try {
        app = data_1.getKubernetesGoalEventData(goalEvent);
    }
    catch (e) {
        return logAndFailDeploy(`No valid goal event data found for ${appId}: ${e.message}`, log, dest);
    }
    dest = destination(goalEvent, app);
    if (!request_1.isKubernetesApplication(app)) {
        return logAndFailDeploy(`No valid Kubernetes goal event data found for ${appId}`, log, dest);
    }
    appId = deployAppId(goalEvent, context, app);
    llog(`Deploying ${appId} to Kubernetes`, logger_1.logger.info, log);
    let resources;
    try {
        resources = await application_1.upsertApplication(app, goalEvent.fulfillment.name);
    }
    catch (e) {
        return logAndFailDeploy(`Failed to deploy ${appId} to Kubernetes: ${e.message}`, log, dest);
    }
    const message = `Successfully deployed ${appId} to Kubernetes`;
    llog(message, logger_1.logger.info, log);
    const description = `Deployed \`${dest}\``;
    const externalUrls = externalUrls_1.appExternalUrls(app);
    try {
        await application_2.syncApplication(app, resources);
    }
    catch (e) {
        return logAndFailDeploy(`Deployed ${appId} to Kubernetes but failed to update sync repo: ${e.message}`, log, dest);
    }
    return { code: 0, description, externalUrls, message };
}
exports.deployApplication = deployApplication;
/** Create a descriptive string for a goal event. */
function deployAppId(g, c, a) {
    const app = (a) ? `/${a.ns}/${a.name}` : "";
    return `${c.workspaceId}:${g.repo.owner}/${g.repo.name}:${g.sha}:${g.fulfillment.name}${app}`;
}
exports.deployAppId = deployAppId;
/**
 * Log to a specific log level method and a progress log.
 *
 * @param ll Levelled log method like `logger.debug`
 * @param log goal progress log
 */
function llog(message, ll, log) {
    log.write(message);
    ll(message);
}
exports.llog = llog;
/**
 * Log and return failure.
 *
 * @param message informative error message
 * @return an ExecuteGoalResult indicating a failed deploy using the provided error message
 */
function logAndFailDeploy(message, log, dest) {
    llog(message, logger_1.logger.error, log);
    const description = `Deploy \`${dest}\` failed`;
    return { code: 1, description, message };
}
/**
 * Create identifying deployment destination from goal environment and
 * fulillment name using [[getCluster]], application namespace, and
 * application name.
 *
 * @param goalEvent SDM goal event to generate desitnation for
 * @param app Kubernetes application object
 * @return The cluster name, application namespace, and application name
 */
function destination(goalEvent, app) {
    const cluster = cluster_1.getCluster(goalEvent.environment, goalEvent.fulfillment.name);
    const nsName = (app) ? `:${app.ns}/${app.name}` : "";
    return `${cluster}${nsName}`;
}
exports.destination = destination;
//# sourceMappingURL=deploy.js.map