"use strict";
/**
 * penguins-eggs
 * classes/families: debian.ts
 * author: Piero Proietti
 * email: piero.proietti@gmail.com
 * license: MIT
 */
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 utils_1 = tslib_1.__importDefault(require("../utils"));
const pacman_1 = tslib_1.__importDefault(require("../pacman"));
const utils_2 = require("../../lib/utils");
const dependencies_1 = require("../../lib/dependencies");
/**
 * Debian
 * @remarks all the utilities
 */
class Debian {
    /**
     * Debian: isInstalledXorg
     * @returns true if xorg is installed
     */
    static isInstalledXorg() {
        return this.packageIsInstalled('xserver-xorg-core');
    }
    /**
     * Debian: isInstalledWayland
     * @returns true if wayland is installed
     */
    static isInstalledWayland() {
        return this.packageIsInstalled('xwayland');
    }
    /**
     * Debian: packages
     * Create array packages to install/remove
     */
    static packages(remove = false, verbose = false) {
        let packages = [];
        const toInstall = [];
        const toRemove = [];
        for (const elem of dependencies_1.depCommon) {
            if (!this.packageIsInstalled(elem)) {
                toInstall.push(elem);
            }
            else {
                toRemove.push(elem);
            }
        }
        const arch = utils_1.default.uefiArch();
        for (const dep of dependencies_1.depArch) {
            if (dep.arch.includes(arch)) {
                if (!this.packageIsInstalled(dep.package)) {
                    toInstall.push(dep.package);
                }
                else {
                    toRemove.push(dep.package);
                }
            }
        }
        /**
         * depending on init/systemd
         */
        const initType = shelljs_1.default.exec('ps --no-headers -o comm 1', { silent: !verbose }).trim();
        for (const dep of dependencies_1.depInit) {
            if (dep.init.includes(initType)) {
                if (!this.packageIsInstalled(dep.package)) {
                    toInstall.push(dep.package);
                }
                else {
                    toRemove.push(dep.package);
                }
            }
        }
        packages = toInstall;
        if (remove) {
            packages = toRemove;
        }
        return packages;
    }
    /**
     * Debian: prerequisitesInstall
     * install prerequisites
     */
    static async prerequisitesInstall(verbose = true) {
        const echo = utils_1.default.setEcho(verbose);
        const retVal = false;
        await (0, utils_2.exec)(`apt-get install --yes ${(0, dependencies_1.array2spaced)(this.packages(false, verbose))}`, echo);
        if (!pacman_1.default.isInstalledGui()) {
            /**
             * live-config-getty-generator
             *
             * Viene rimosso in naked, altrimenti non funziona il login
             * generando un errore getty.
             * Sarebbe utile individuarne le ragioni, forse rompe anche sul desktop
             * non permettendo di cambiare terminale e loggarsi
             *
             * A che serve?
             */
            const fileToRemove = '/lib/systemd/system-generators/live-config-getty-generator';
            if (node_fs_1.default.existsSync(fileToRemove)) {
                await (0, utils_2.exec)(`rm ${fileToRemove}`);
            }
        }
        return retVal;
    }
    /**
     * Debian: calamaresInstall
     */
    static async calamaresInstall(verbose = true) {
        const echo = utils_1.default.setEcho(verbose);
        try {
            await (0, utils_2.exec)('apt-get update --yes', echo);
        }
        catch {
            utils_1.default.error('Debian.calamaresInstall() apt-get update --yes '); // + e.error as string)
        }
        try {
            await (0, utils_2.exec)(`apt-get install --yes ${(0, dependencies_1.array2spaced)(this.debs4calamares)}`, echo);
        }
        catch {
            utils_1.default.error(`Debian.calamaresInstall() apt-get install --yes ${(0, dependencies_1.array2spaced)(this.debs4calamares)}`); // + e.error)
        }
    }
    /**
     * Debian: calamaresPolicies
     */
    static async calamaresPolicies() {
        const policyFile = '/usr/share/polkit-1/actions/com.github.calamares.calamares.policy';
        await (0, utils_2.exec)(`sed -i 's/auth_admin/yes/' ${policyFile}`);
    }
    /**
     * Debian: calamaresRemove
     */
    static async calamaresRemove(verbose = true) {
        const echo = utils_1.default.setEcho(verbose);
        const retVal = false;
        if (node_fs_1.default.existsSync('/etc/calamares')) {
            await (0, utils_2.exec)('rm /etc/calamares -rf', echo);
        }
        await (0, utils_2.exec)('apt-get remove --purge --yes calamares', echo);
        await (0, utils_2.exec)('apt-get autoremove --yes', echo);
        return retVal;
    }
    /**
     * Debian: liveInstallerPolicies
     * liveInstallerPolicies is NOT USED
     */
    static async liveInstallerPolicies() {
        const policyFile = '/usr/share/polkit-1/actions/com.github.pieroproietti.penguins-eggs.policy';
        await (0, utils_2.exec)(`sed -i 's/auth_admin/yes/' ${policyFile}`);
    }
    /**
     * Debian: packageIsInstalled
     * restuisce VERO se il pacchetto è installato
     * @param debPackage
     */
    static packageIsInstalled(debPackage) {
        let installed = false;
        const cmd = `/usr/bin/dpkg -s ${debPackage} | grep Status:`;
        const stdout = shelljs_1.default.exec(cmd, { silent: true }).stdout.trim();
        if (stdout === 'Status: install ok installed') {
            installed = true;
        }
        return installed;
    }
    /**
     * Debian: packageInstall
     * @param packageName {string} Pacchetto Debian da installare
     * @returns {boolean} True if success
     */
    static async packageInstall(packageName) {
        let retVal = false;
        if (shelljs_1.default.exec(`/usr/bin/apt-get install -y ${packageName}`, { silent: true }) === '0') {
            retVal = true;
        }
        return retVal;
    }
    /**
     * Debian: packageAptAvailable
     * return TRUE if package is present on repository
     * @param debPackage
     */
    static async packageAptAvailable(packageName) {
        let available = false;
        const cmd = `apt-cache show ${packageName} | grep Package:`;
        const test = `Package: ${packageName}`;
        const stdout = shelljs_1.default.exec(cmd, { silent: true }).stdout.trim();
        if (stdout === test) {
            available = true;
        }
        return available;
    }
    /**
     * Debian: packageAptLast
     * @param debPackage
     * @returns version
     */
    static async packageAptLast(debPackage) {
        let version = '';
        const cmd = `apt-cache show ${debPackage} | grep Version:`;
        const stdout = shelljs_1.default.exec(cmd, { silent: true }).stdout.trim();
        version = stdout.slice(9);
        // console.log('===================================')
        // console.log('[' + version + ']')
        // console.log('===================================')
        return version;
    }
}
Debian.debs4calamares = ['calamares', 'qml-module-qtquick2', 'qml-module-qtquick-controls'];
exports.default = Debian;
