"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.processResult = exports.prepareInputAndOutput = exports.containerEnvVars = exports.runningAsGoogleCloudFunction = exports.runningInK8s = void 0;
const GraphClient_1 = require("@atomist/automation-client/lib/spi/graph/GraphClient");
const fs = require("fs-extra");
const _ = require("lodash");
const path = require("path");
const namespace_1 = require("../../../pack/k8s/support/namespace");
const projectVersioner_1 = require("../../delivery/build/local/projectVersioner");
const ImageLink_1 = require("../../util/webhook/ImageLink");
const container_1 = require("./container");
/**
 * Simple test to see if SDM is running in Kubernetes.  It is called
 * from a non-async function, so it must be non-async.
 *
 * @return `true` if process is running in Kubernetes, `false` otherwise.
 */
function runningInK8s() {
    return fs.pathExistsSync(namespace_1.K8sNamespaceFile);
}
exports.runningInK8s = runningInK8s;
/**
 * Simple test to see if SDM is running as a Google Cloud Function.
 *
 * @return `true` if process is running as Google Cloud Function,
 * `false` otherwise.
 */
function runningAsGoogleCloudFunction() {
    return !!process.env.K_SERVICE && !!process.env.K_REVISION;
}
exports.runningAsGoogleCloudFunction = runningAsGoogleCloudFunction;
/**
 * Return environment variables required by the container goal
 * execution machinery.
 *
 * @param goalEvent SDM goal event being executed as a container goal
 * @param ctx SDM context for goal execution
 * @return SDM goal environment variables
 */
async function containerEnvVars(goalEvent, ctx, projectDir = container_1.ContainerProjectHome, inputDir = container_1.ContainerInput, outputDir = container_1.ContainerOutput) {
    const version = await projectVersioner_1.getGoalVersion({
        owner: goalEvent.repo.owner,
        repo: goalEvent.repo.name,
        providerId: goalEvent.repo.providerId,
        sha: goalEvent.sha,
        branch: goalEvent.branch,
        context: ctx.context,
    });
    // This should probably go into a different place but ok for now
    if (!!version) {
        _.set(goalEvent, "push.after.version", version);
    }
    return [
        {
            name: "ATOMIST_WORKSPACE_ID",
            value: ctx.context.workspaceId,
        },
        {
            name: "ATOMIST_SLUG",
            value: `${goalEvent.repo.owner}/${goalEvent.repo.name}`,
        },
        {
            name: "ATOMIST_OWNER",
            value: goalEvent.repo.owner,
        },
        {
            name: "ATOMIST_REPO",
            value: goalEvent.repo.name,
        },
        {
            name: "ATOMIST_SHA",
            value: goalEvent.sha,
        },
        {
            name: "ATOMIST_BRANCH",
            value: goalEvent.branch,
        },
        {
            name: "ATOMIST_VERSION",
            value: version,
        },
        {
            name: "ATOMIST_GOAL",
            value: `${inputDir}/goal.json`,
        },
        {
            name: "ATOMIST_RESULT",
            value: `${outputDir}/result.json`,
        },
        {
            name: "ATOMIST_INPUT_DIR",
            value: inputDir,
        },
        {
            name: "ATOMIST_OUTPUT_DIR",
            value: outputDir,
        },
        {
            name: "ATOMIST_PROJECT_DIR",
            value: projectDir,
        },
    ].filter(e => !!e.value);
}
exports.containerEnvVars = containerEnvVars;
async function prepareInputAndOutput(input, output, gi) {
    try {
        await fs.emptyDir(input);
    }
    catch (e) {
        e.message = `Failed to empty directory '${input}'`;
        throw e;
    }
    try {
        await fs.writeJson(path.join(input, "goal.json"), gi.goalEvent, { spaces: 2 });
    }
    catch (e) {
        e.message = `Failed to write metadata to '${input}'`;
        try {
            await fs.remove(input);
        }
        catch (err) {
            e.message += `; Failed to clean up '${input}': ${err.message}`;
        }
        throw e;
    }
    try {
        await fs.emptyDir(output);
    }
    catch (e) {
        e.message = `Failed to empty directory '${output}'`;
        throw e;
    }
}
exports.prepareInputAndOutput = prepareInputAndOutput;
async function processResult(result, gi) {
    const { goalEvent, context } = gi;
    if (!!result) {
        if (result.SdmGoal) {
            const goal = result.SdmGoal;
            const r = {
                state: goal.state,
                phase: goal.phase,
                description: goal.description,
                externalUrls: goal.externalUrls,
                data: convertData(goal.data),
            };
            const builds = _.get(goal, "push.builds");
            if (!!builds) {
                for (const build of builds) {
                    await ImageLink_1.postBuildWebhook(goalEvent.repo.owner, goalEvent.repo.name, goalEvent.branch, goalEvent.sha, build.status, context.workspaceId);
                }
            }
            const version = _.get(goal, "push.after.version");
            if (!!version) {
                const sdmVersion = {
                    sha: goalEvent.sha,
                    branch: gi.goalEvent.branch,
                    version,
                    repo: {
                        owner: goalEvent.repo.owner,
                        name: goalEvent.repo.name,
                        providerId: goalEvent.repo.providerId,
                    },
                };
                await gi.context.graphClient.mutate({
                    name: "UpdateSdmVersion",
                    variables: {
                        version: sdmVersion,
                    },
                    options: GraphClient_1.MutationNoCacheOptions,
                });
            }
            return r;
        }
        else {
            return Object.assign(Object.assign({}, result), { data: convertData(result.data) });
        }
    }
    return undefined;
}
exports.processResult = processResult;
function convertData(data) {
    return !!data && typeof data !== "string" ? JSON.stringify(data) : data;
}
//# sourceMappingURL=util.js.map