"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const FSE = tslib_1.__importStar(require("fs-extra"));
const hyphenate_1 = tslib_1.__importDefault(require("hyphenate"));
const shared_1 = require("../../../bld/shared");
function SSH_CONFIG_HOST({ displayName, port, }) {
    return `remote-workspace-${hyphenate_1.default(displayName, { lowerCase: true }) ||
        'remote-workspace'}-${port}`;
}
exports.SSH_CONFIG_HOST = SSH_CONFIG_HOST;
class SSHConfig {
    constructor(options) {
        this.options = options;
    }
    update(workspaces) {
        let { remoteHost, filePath } = this.options;
        let remoteDevSSHConfigContent = `\
# remote-workspace:start

${workspaces
            .map(workspace => {
            let projectsConfigsContent = shared_1.groupWorkspaceProjectConfigs(workspace)
                .configs.map(config => `  ${config}\n`)
                .join('');
            return `\
Host ${SSH_CONFIG_HOST(workspace)}
  User root
  HostName ${remoteHost}
  HostkeyAlias remote-workspace-${remoteHost}
  ForwardAgent yes
  Port ${workspace.port}
${projectsConfigsContent}`;
        })
            .join('\n')}
# remote-workspace:end`;
        let sshConfigContent = this.load(true);
        let replaced = false;
        let updatedSSHConfigContent = sshConfigContent.replace(/^# remote-workspace:start$[\s\S]*^# remote-workspace:end$/m, () => {
            replaced = true;
            return remoteDevSSHConfigContent;
        });
        if (!replaced) {
            if (updatedSSHConfigContent.trim()) {
                updatedSSHConfigContent += '\n';
            }
            else {
                updatedSSHConfigContent = '';
            }
            updatedSSHConfigContent += `${remoteDevSSHConfigContent}\n`;
        }
        if (updatedSSHConfigContent !== sshConfigContent) {
            FSE.outputFileSync(filePath, updatedSSHConfigContent);
            console.info('SSH configuration updated.');
        }
    }
    load(toIgnoreCache) {
        let { filePath } = this.options;
        let content = this.content;
        if (toIgnoreCache || typeof content !== 'string') {
            content = FSE.existsSync(filePath)
                ? FSE.readFileSync(filePath, 'utf8')
                : '';
            this.content = content;
        }
        return content;
    }
}
exports.SSHConfig = SSHConfig;
//# sourceMappingURL=ssh-config.js.map