"use strict";
/**
 * penguins-eggs: fisherman.ts
 *
 * author: Piero Proietti
 * mail: piero.proietti@gmail.com
 */
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
const node_path_1 = tslib_1.__importDefault(require("node:path"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const settings_1 = require("./fisherman-helper/settings");
const utils_1 = require("../../lib/utils");
class Fisherman {
    constructor(distro, installer, verbose = false) {
        this.installer = {};
        this.verbose = false;
        this.distro = distro;
        this.installer = installer;
        this.verbose = verbose;
    }
    /**
     * write setting
     */
    async createCalamaresSettings(theme = 'eggs', isClone = false) {
        await (0, settings_1.settings)(this.installer.template, this.installer.configRoot, theme, isClone);
    }
    /**
     *
     * @param name
     */
    async shellprocess(name) {
        const moduleSource = node_path_1.default.resolve(__dirname, this.installer.templateModules + 'shellprocess_' + name + '.yml');
        const moduleDest = this.installer.modules + 'shellprocess_' + name + '.conf';
        if (node_fs_1.default.existsSync(moduleSource)) {
            if (this.verbose)
                this.show(name, 'shellprocess', moduleDest);
            shelljs_1.default.cp(moduleSource, moduleDest);
        }
        else if (this.verbose) {
            console.log(`calamares: ${name} shellprocess, nothing to do`);
        }
    }
    /**
     *
     * @param name
     */
    async contextualprocess(name) {
        const moduleSource = node_path_1.default.resolve(__dirname, this.installer.templateModules + name + '_context.yml');
        const moduleDest = this.installer.modules + name + '_context.conf';
        if (node_fs_1.default.existsSync(moduleSource)) {
            if (this.verbose)
                this.show(name, 'contextualprocess', moduleDest);
            shelljs_1.default.cp(moduleSource, moduleDest);
        }
        else if (this.verbose) {
            console.log(`calamares: ${name} contextualprocess, nothing to do!`);
        }
    }
    /**
     *
     * @param name
     * @param replaces [['search','replace']]
     */
    async buildModule(name, vendor = '') {
        let moduleSource = node_path_1.default.resolve(__dirname, this.installer.templateModules + name + '.yml');
        /**
         * We need vendor here to have possibility to load custom modules for calamares
         * the custom modules live in: /addons/vendor/theme/calamares/modules
         * and - if exist - take priority on distro modules on /conf/distros/calamares/modules
         *
         * example:
         *
         * ./addons/openos/theme/calamares/modules/partition.yml
         * take place of:
         * ./conf/distros/bullseye/calamares/modules/partition.yml
         * and end in:
         * /etc/calamares/modules/partition.conf
         *
         * And we solve the issue of Sebastien who need btrfs
         *
         */
        if (vendor !== 'eggs') {
            let customModuleSource = node_path_1.default.resolve(__dirname, `../../../addons/${vendor}/theme/calamares/modules/${name}.yml`);
            if (vendor.includes('/')) {
                customModuleSource = `${vendor}/theme/calamares/modules/${name}.yml`;
            }
            if (node_fs_1.default.existsSync(customModuleSource)) {
                moduleSource = customModuleSource;
            }
        }
        const moduleDest = this.installer.modules + name + '.conf';
        if (node_fs_1.default.existsSync(moduleSource)) {
            if (this.verbose) {
                this.show(name, 'module', moduleDest);
            }
            shelljs_1.default.cp(moduleSource, moduleDest);
        }
        else if (this.verbose) {
            console.log('unchanged: ' + chalk_1.default.greenBright(name));
        }
    }
    /**
     *
     * @param name
     * @param isScript
     */
    async buildCalamaresModule(name, isScript = true, theme = 'eggs') {
        let moduleTemplate = node_path_1.default.resolve(__dirname, this.installer.templateMultiarch + name);
        if (theme !== 'eggs') {
            moduleTemplate = theme + '/theme/calamares/calamares-modules/' + name;
        }
        const moduleDest = this.installer.multiarchModules + name;
        const moduleScript = `/usr/sbin/${name}.sh`;
        if (this.verbose)
            this.show(name, 'module', moduleDest);
        if (!node_fs_1.default.existsSync(moduleDest)) {
            node_fs_1.default.mkdirSync(moduleDest);
        }
        shelljs_1.default.cp(`${moduleTemplate}/module.yml`, `${moduleDest}/module.desc`);
        if (isScript) {
            shelljs_1.default.cp(`${moduleTemplate}/${name}.sh`, moduleScript);
            await (0, utils_1.exec)(`chmod +x ${moduleScript}`);
        }
        return moduleScript;
    }
    /**
     *
     * @param name
     */
    async buildCalamaresPy(name) {
        const moduleSource = node_path_1.default.resolve(__dirname, this.installer.templateMultiarch + '/' + name);
        const moduleDest = this.installer.multiarchModules + name;
        if (this.verbose)
            this.show(name, 'python', moduleDest);
        if (!node_fs_1.default.existsSync(moduleDest)) {
            node_fs_1.default.mkdirSync(moduleDest);
        }
        shelljs_1.default.cp(`${moduleSource}/module.yml`, `${moduleDest}/module.desc`);
        shelljs_1.default.cp(`${moduleSource}/${name}.yml`, `${moduleDest}/${name}.conf`);
        shelljs_1.default.cp(`${moduleSource}/main.py`, moduleDest);
        await (0, utils_1.exec)(`chmod +x ${moduleSource}/main.py`);
    }
    /**
     *
     * @param module
     * @param type
     * @param path
     */
    show(name, type, path) {
        switch (type) {
            case 'module': {
                console.log('fisherman: ' + chalk_1.default.yellow(name) + ' module in ' + chalk_1.default.yellow(path));
                break;
            }
            case 'calamares_module': {
                console.log('fisherman: ' + chalk_1.default.cyanBright(name) + ' calamares_module in ' + chalk_1.default.cyanBright(path));
                break;
            }
            case 'shellprocess': {
                console.log('fisherman: ' + chalk_1.default.green(name) + ' shellprocess in ' + chalk_1.default.green(path));
                break;
            }
            case 'contextualprocess': {
                console.log('fisherman: ' + chalk_1.default.cyanBright(name) + ' shellprocess in ' + chalk_1.default.cyanBright(path));
                break;
            }
            // No default
        }
    }
    /**
     * ====================================================================================
     * M O D U L E S
     * ====================================================================================
     */
    /**
     * Al momento rimane con la vecchia configurazione
     */
    async moduleFinished() {
        const name = 'finished';
        await this.buildModule(name);
        const restartNowCommand = 'reboot';
        shelljs_1.default.sed('-i', '{{restartNowCommand}}', restartNowCommand, this.installer.modules + name + '.conf');
    }
    /**
     * Al momento rimane con la vecchia configurazione
     */
    async moduleUnpackfs() {
        const name = 'unpackfs';
        this.buildModule(name);
        shelljs_1.default.sed('-i', '{{source}}', this.distro.liveMediumPath + this.distro.squashfs, this.installer.modules + name + '.conf');
    }
    /**
     * usa i moduli-ts
     */
    async moduleDisplaymanager() {
        const name = 'displaymanager';
        const displaymanager = require('./fisherman-helper/displaymanager').displaymanager;
        this.buildModule(name);
        shelljs_1.default.sed('-i', '{{displaymanagers}}', displaymanager(), this.installer.modules + name + '.conf');
    }
    /**
     * usa i moduli-ts
     */
    async modulePackages(distro, release = false) {
        const name = 'packages';
        const removePackages = require('./fisherman-helper/packages').remove;
        const tryInstall = require('./fisherman-helper/packages').tryInstall;
        this.buildModule(name);
        const yamlInstall = tryInstall(distro);
        let yamlRemove = '';
        if (release) {
            yamlRemove = removePackages(distro);
        }
        let operations = '';
        if (yamlRemove !== '' || yamlInstall !== '') {
            operations = 'operations:\n' + yamlRemove + yamlInstall;
        }
        shelljs_1.default.sed('-i', '{{operations}}', operations, this.installer.modules + name + '.conf');
    }
    /**
     * Al momento rimane con la vecchia configurazione
     */
    async moduleRemoveuser(username) {
        const name = 'removeuser';
        this.buildModule(name);
        shelljs_1.default.sed('-i', '{{username}}', username, this.installer.modules + name + '.conf');
    }
}
exports.default = Fisherman;
