"use strict";
/**
 *
 * @param theme
 * @param isClone
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.settings = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
const displaymanager_1 = require("./displaymanager");
const utils_1 = tslib_1.__importDefault(require("../../utils"));
const installer_1 = require("../installer");
/**
 *
 * @param src
 * @param dest
 * @param theme
 * @param isClone
 */
async function settings(src, dest, theme = 'eggs', isClone = false) {
    let branding = theme;
    let settingsSrc = src + 'settings.yml';
    if (theme.includes('/')) {
        branding = theme.slice(Math.max(0, theme.lastIndexOf('/') + 1));
    }
    const settingsDest = dest + 'settings.conf';
    shelljs_1.default.cp(settingsSrc, settingsDest);
    let hasSystemd = '# ';
    if (utils_1.default.isSystemd()) {
        hasSystemd = '- ';
    }
    let createUsers = '- ';
    if (isClone) {
        createUsers = '# ';
    }
    let hasDisplaymanager = '# ';
    if ((0, displaymanager_1.displaymanager)() !== '') {
        hasDisplaymanager = '- ';
    }
    shelljs_1.default.sed('-i', '{{hasSystemd}}', hasSystemd, settingsDest);
    shelljs_1.default.sed('-i', '{{hasDisplaymanager}}', hasDisplaymanager, settingsDest);
    shelljs_1.default.sed('-i', '{{branding}}', branding, settingsDest);
    shelljs_1.default.sed('-i', '{{createUsers}}', createUsers, settingsDest);
    /**
     * cfsAppend
     */
    const cfsPath = `${theme}/theme/calamares/cfs.yml`;
    if (fs_1.default.existsSync(cfsPath)) {
        cfsAppend(cfsPath);
    }
}
exports.settings = settings;
/**
 *
 */
function cfsAppend(cfs) {
    const configRoot = (0, installer_1.installer)().configRoot + 'settings.conf';
    let soContent = fs_1.default.readFileSync(configRoot, 'utf8');
    let so = js_yaml_1.default.load(soContent);
    const cfsContent = fs_1.default.readFileSync(cfs, 'utf8');
    const cfsSteps = js_yaml_1.default.load(cfsContent);
    const execSteps = so.sequence[1].exec;
    for (const execStep of execSteps) {
        if (execStep.includes('umount')) {
            so.sequence[1].exec.pop(); // OK remove umount
            /**
             * insert cfsStep
             */
            for (const cfsStep of cfsSteps) {
                so.sequence[1].exec.push(cfsStep);
            }
            so.sequence[1].exec.push('end-cfs'); // we will replace with umount
        }
    }
    // ***
    fs_1.default.writeFileSync(configRoot, js_yaml_1.default.dump(so), 'utf-8');
    shelljs_1.default.sed('-i', 'end-cfs', 'umount', configRoot);
}
