"use strict";
/*
 * Copyright 2020 NEM
 *
 * 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.AgentCertificateService = void 0;
const path_1 = require("path");
const logger_1 = require("../logger");
const LoggerFactory_1 = require("../logger/LoggerFactory");
const BootstrapUtils_1 = require("./BootstrapUtils");
const logger = LoggerFactory_1.default.getLogger(logger_1.LogType.System);
class AgentCertificateService {
    constructor(root, params) {
        this.root = root;
        this.params = params;
    }
    async run(symbolServerToolsImage, name, customCertFolder) {
        const copyFrom = `${this.root}/config/agent-cert`;
        const certFolder = customCertFolder || BootstrapUtils_1.BootstrapUtils.getTargetNodesFolder(this.params.target, false, name, 'agent');
        await BootstrapUtils_1.BootstrapUtils.mkdir(certFolder);
        const generatedContext = { name };
        await BootstrapUtils_1.BootstrapUtils.generateConfiguration(generatedContext, copyFrom, certFolder, []);
        const command = this.createCertCommands('/data');
        await BootstrapUtils_1.BootstrapUtils.writeTextFile(path_1.join(certFolder, 'createAgentCertificate.sh'), command);
        const cmd = ['bash', 'createAgentCertificate.sh'];
        const binds = [`${path_1.resolve(certFolder)}:/data:rw`];
        const userId = await BootstrapUtils_1.BootstrapUtils.resolveDockerUserFromParam(this.params.user);
        const { stdout, stderr } = await BootstrapUtils_1.BootstrapUtils.runImageUsingExec({
            image: symbolServerToolsImage,
            userId: userId,
            workdir: '/data',
            cmds: cmd,
            binds: binds,
        });
        if (stdout.indexOf('Certificate Created') < 0) {
            logger.info(BootstrapUtils_1.BootstrapUtils.secureString(stdout));
            logger.error(BootstrapUtils_1.BootstrapUtils.secureString(stderr));
            throw new Error('Certificate creation failed. Check the logs!');
        }
        logger.info(`Agent Certificate for node ${name} created`);
    }
    createCertCommands(target) {
        return `set -e
        cd ${target}
# Creating a self signed certificate for the agent. This will be created by bootstrap when setting up a supernode
openssl genrsa -out agent-key.pem 4096
openssl req -new -config agent.cnf -key agent-key.pem -out agent-csr.pem
openssl x509 -req -extfile agent.cnf -days 999 -in agent-csr.pem -out agent-crt.pem -signkey agent-key.pem

rm createAgentCertificate.sh
rm agent-csr.pem
rm agent.cnf

echo "Certificate Created"
`;
    }
}
exports.AgentCertificateService = AgentCertificateService;
