"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.execute = void 0;
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const string_1 = require("@atomist/automation-client/lib/internal/util/string");
const fs = require("fs-extra");
const _ = require("lodash");
const os = require("os");
const path = require("path");
const withProject_1 = require("../../../api-helper/project/withProject");
const GoalWithFulfillment_1 = require("../../../api/goal/GoalWithFulfillment");
const resolvePlaceholder_1 = require("../../machine/yaml/resolvePlaceholder");
const container_1 = require("./container");
const provider_1 = require("./provider");
const util_1 = require("./util");
function execute(name, registration) {
    const uniqueName = name.replace(/ /g, "_");
    const executeGoal = GoalWithFulfillment_1.goal({ displayName: name, uniqueName }, withProject_1.doWithProject(async (gi) => {
        const { goalEvent, project } = gi;
        // Resolve placeholders
        const registrationToUse = _.cloneDeep(registration);
        await configuration_1.resolvePlaceholders(registrationToUse, value => resolvePlaceholder_1.resolvePlaceholder(value, gi.goalEvent, gi, gi.parameters));
        const env = Object.assign({}, process.env);
        // Mount the secrets
        let secrets;
        if (!!registrationToUse.secrets) {
            secrets = await provider_1.prepareSecrets({ secrets: registrationToUse.secrets }, gi);
            secrets.env.forEach(e => env[e.name] = e.value);
            for (const f of secrets.files) {
                await fs.ensureDir(path.dirname(f.mountPath));
                await fs.writeFile(f.mountPath, f.value);
            }
        }
        const goalName = goalEvent.uniqueName.split("#")[0].toLowerCase();
        const namePrefix = "sdm-";
        const nameSuffix = `-${goalEvent.goalSetId.slice(0, 7)}-${goalName}`;
        const tmpDir = path.join(os.homedir(), ".atomist", "tmp", goalEvent.repo.owner, goalEvent.repo.name, goalEvent.goalSetId);
        const inputDir = path.join(tmpDir, `${namePrefix}tmp-${string_1.guid()}${nameSuffix}`);
        const outputDir = path.join(tmpDir, `${namePrefix}tmp-${string_1.guid()}${nameSuffix}`);
        await util_1.prepareInputAndOutput(inputDir, outputDir, gi);
        (await util_1.containerEnvVars(goalEvent, gi, project.baseDir, inputDir, outputDir)).forEach(e => env[e.name] = e.value);
        try {
            const result = await gi.spawn(registrationToUse.cmd, registrationToUse.args, { env });
            if (result.code === 0) {
                const outputFile = path.join(outputDir, "result.json");
                if ((await fs.pathExists(outputFile))) {
                    return await util_1.processResult(await fs.readJson(outputFile), gi);
                }
            }
            else {
                return {
                    code: result.code,
                };
            }
            // TODO catch
        }
        finally {
            // Cleanup secrets;
            if (!!secrets) {
                for (const f of secrets.files) {
                    await fs.unlink(f.mountPath);
                }
            }
            // Delete tmpDir
            if (!!tmpDir) {
                await fs.remove(tmpDir);
            }
        }
        return {
            code: 0,
        };
    }, {
        readOnly: false,
        detachHead: true,
    }), { progressReporter: container_1.ContainerProgressReporter });
    return executeGoal;
}
exports.execute = execute;
//# sourceMappingURL=execute.js.map