"use strict";
/**
 * penguins-eggs
 * class: xdg.ts
 * author: Piero Proietti
 * email: piero.proietti@gmail.com
 * license: MIT
 */
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
const node_path_1 = tslib_1.__importDefault(require("node:path"));
const pacman_1 = tslib_1.__importDefault(require("./pacman"));
const utils_1 = tslib_1.__importDefault(require("./utils"));
const n8_1 = tslib_1.__importDefault(require("./n8"));
// libraries
const utils_2 = require("../lib/utils");
const distro_1 = tslib_1.__importDefault(require("./distro"));
const xdg_dirs = ['DESKTOP', 'DOWNLOAD', 'TEMPLATES', 'PUBLICSHARE', 'DOCUMENTS', 'MUSIC', 'PICTURES', 'VIDEOS'];
/**
 * Xdg: xdg-user-dirs, etc
 * @remarks all the utilities
 */
class Xdg {
    /**
     *
     * @param xdg_dir
     */
    static traduce(xdg_dir = '', traduce = true) {
        let retval = '';
        if (traduce === false) {
            // Capitalize
            retval = xdg_dir.charAt(0).toUpperCase() + xdg_dir.slice(1).toLowerCase();
            console.log(retval);
        }
        else {
            xdg_dirs.forEach(async (dir) => {
                if (dir === xdg_dir) {
                    retval = node_path_1.default.basename(shelljs_1.default.exec(`sudo -u ${await utils_1.default.getPrimaryUser()} xdg-user-dir ${dir}`, { silent: true }).stdout.trim());
                }
            });
        }
        return retval;
    }
    /**
     *
     * @param user
     * @param chroot
     * @param verbose
     */
    static async create(user, chroot, traduce = true, verbose = false) {
        const echo = utils_1.default.setEcho(verbose);
        /**
         * Creo solo la cartella DESKTOP perchè serve per i link, eventualmente posso creare le altre
         * ma c'è il problema di traduce/non traduce
         */
        xdg_dirs.forEach(async (dir) => {
            if (dir === 'DESKTOP') {
                await Xdg.mk(chroot, `/home/${user}/` + this.traduce(dir, traduce), verbose);
            }
        });
    }
    /**
     *
     * @param chroot
     * @param path
     * @param verbose
     */
    static async mk(chroot, path, verbose = false) {
        const echo = utils_1.default.setEcho(verbose);
        if (!node_fs_1.default.existsSync(chroot + path)) {
            await (0, utils_2.exec)(`mkdir ${chroot}${path}`, echo);
        }
    }
    /**
     *
     * @param olduser
     * @param newuser
     * @param chroot
     */
    static async autologin(olduser, newuser, chroot = '/') {
        if (pacman_1.default.isInstalledGui()) {
            /**
             * SLIM & SLIMSKI
             */
            let slimConf = '';
            if (pacman_1.default.packageIsInstalled('slim')) {
                slimConf = 'slim.conf';
                if (node_fs_1.default.existsSync('/etc/slim.local.conf')) {
                    slimConf = 'slim.local.conf';
                }
            }
            if (pacman_1.default.packageIsInstalled('slimski')) {
                slimConf = 'slimski.conf';
                if (node_fs_1.default.existsSync('/etc/slimski.local.conf')) {
                    slimConf = 'slimski.local.conf';
                }
            }
            if (slimConf !== '') {
                shelljs_1.default.sed('-i', 'auto_login no', 'auto_login yes', `${chroot}/etc/${slimConf}`);
                shelljs_1.default.sed('-i', `default_user ${olduser}`, `default_user ${newuser}`, `${chroot}/etc/${slimConf}`);
            }
            /**
             * LIGHTDM
             */
            if (pacman_1.default.packageIsInstalled('lightdm')) {
                const dc = `${chroot}/etc/lightdm/`;
                const files = node_fs_1.default.readdirSync(dc);
                for (const elem of files) {
                    const curFile = dc + elem;
                    if (!n8_1.default.isDirectory(curFile)) {
                        const content = node_fs_1.default.readFileSync(curFile, 'utf8');
                        const find = '[Seat:*]';
                        if (content.includes(find)) {
                            shelljs_1.default.sed('-i', `autologin-user=${olduser}`, `autologin-user=${newuser}`, curFile);
                        }
                    }
                }
            }
            /**
             * SDDM
             */
            if (pacman_1.default.packageIsInstalled('sddm')) {
                let sddmChanged = false;
                const curFile = `${chroot}/etc/sddm.conf`;
                if (node_fs_1.default.existsSync(curFile)) {
                    const content = node_fs_1.default.readFileSync(curFile, 'utf8');
                    const find = '[Autologin]';
                    if (content.includes(find)) {
                        shelljs_1.default.sed('-i', `User=${olduser}`, `User=${newuser}`, curFile);
                        sddmChanged = true;
                    }
                }
                if (!sddmChanged) {
                    const dc = `${chroot}/etc/sddm.conf.d/`;
                    if (node_fs_1.default.existsSync(dc)) {
                        const files = node_fs_1.default.readdirSync(dc);
                        for (const elem of files) {
                            const curFile = dc + elem;
                            const content = node_fs_1.default.readFileSync(curFile, 'utf8');
                            const find = '[Autologin]';
                            if (content.includes(find)) {
                                shelljs_1.default.sed('-i', `User=${olduser}`, `User=${newuser}`, curFile);
                                sddmChanged = true;
                            }
                        }
                    }
                }
                // sddm.conf don't exists, generate it
                if (!sddmChanged) {
                    let session = 'plasma';
                    if (pacman_1.default.isInstalledWayland()) {
                        session = 'plasma-wayland';
                    }
                    const content = `[Autologin]\nUser=${newuser}\nSession=${session}\n`;
                    const curFile = `${chroot}/etc/sddm.conf`;
                    node_fs_1.default.writeFileSync(curFile, content, 'utf8');
                }
            }
            /**
             * GDM/GDM3
             * in manjaro è /etc/gdm/custom.conf
             */
            if (pacman_1.default.packageIsInstalled('gdm') || pacman_1.default.packageIsInstalled('gdm3')) {
                let gdmConf = `${chroot}/etc/gdm3`;
                if (pacman_1.default.packageIsInstalled('gdm3')) {
                    gdmConf = `${chroot}/etc/gdm3`;
                }
                else if (pacman_1.default.packageIsInstalled('gdm')) {
                    gdmConf = `${chroot}/etc/gdm`;
                }
                if (node_fs_1.default.existsSync(`${gdmConf}/custom.conf`)) {
                    gdmConf += '/custom.conf';
                }
                else if (node_fs_1.default.existsSync(`${gdmConf}/daemon.conf`)) {
                    gdmConf += '/daemon.conf';
                }
                else {
                    gdmConf = `}/etc/${gdmConf}/custom.conf`;
                }
                const content = `[daemon]\nAutomaticLoginEnable=true\nAutomaticLogin=${newuser}\n`;
                utils_1.default.write(gdmConf, content);
            }
        }
    }
    /**
     * Copia della configurazione in /etc/skel
     * @param user
     * @param verbose
     */
    static async skel(user, verbose = false) {
        const echo = utils_1.default.setEcho(verbose);
        // Remove and create /etc/skel
        await (0, utils_2.exec)('rm /etc/skel -rf', echo);
        await (0, utils_2.exec)('mkdir -p /etc/skel', echo);
        // copy .bash_logout, .bashrc and .profile to /etc/skel
        await (0, utils_2.exec)(`cp /home/${user}/.bash_logout /etc/skel`, echo);
        await (0, utils_2.exec)(`cp /home/${user}/.bashrc /etc/skel`, echo);
        await (0, utils_2.exec)(`cp /home/${user}/.profile /etc/skel`, echo);
        /**
         * copy desktop configuration
         */
        if (pacman_1.default.packageIsInstalled('gnome-session')) {
            // we need a more clean solution
            await rsyncIfExist(`/home/${user}/.config`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.gtkrc-2.0`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('cinnamon-common')) {
            // before the check was against cinnamon-core
            // use .cinnamon NOT cinnamon/
            await rsyncIfExist(`/home/${user}/.config`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.cinnamon`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('plasma-desktop')) {
            // use .kde NOT .kde/
            await rsyncIfExist(`/home/${user}/.config`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.kde`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('lxde-core')) {
            // we need a more clean solution
            await rsyncIfExist(`/home/${user}/.config`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.gtkrc-2.0`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('lxqt-session')) {
            // we need a more clean solution
            await rsyncIfExist(`/home/${user}/.config/lxqt`, '/etc/skel/.config', verbose);
            await rsyncIfExist(`/home/${user}/.gtkrc-2.0`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('mate-session-manager')) {
            // we need a more clean solution
            await rsyncIfExist(`/home/${user}/.config`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.gtkrc-2.0`, '/etc/skel', verbose);
        }
        else if (pacman_1.default.packageIsInstalled('xfce4-session')) {
            // use .config/xfce4 NOT .config/xfce4/
            await rsyncIfExist(`/home/${user}/.config/xfce4`, '/etc/skel/.config', verbose);
            await (0, utils_2.exec)('mkdir /etc/skel/.local/share -p', echo);
            await rsyncIfExist(`/home/${user}/.local/share/recently-used.xbel`, '/etc/skel/.local/share', verbose);
        }
        /**
         * special cases
         */
        // waydroid
        if (node_fs_1.default.existsSync(`/home/${user}/waydroid-package-manager`)) {
            await rsyncIfExist(`/home/${user}/waydroid-package-manager`, '/etc/skel', verbose);
        }
        // LinuxFX
        if (node_fs_1.default.existsSync(`/home/${user}/.linuxfx`)) {
            // we need to copy: .linuxfx ,kde and ,cinnamon
            await rsyncIfExist(`/home/${user}/.cinnamon`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.kde`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.linuxfx`, '/etc/skel', verbose);
            await rsyncIfExist(`/home/${user}/.local`, '/etc/skel', verbose);
        }
        await (0, utils_2.exec)('chown root:root /etc/skel -R', echo);
        await (0, utils_2.exec)('chmod a+rwx,g-w,o-w /etc/skel/ -R', echo);
        await execIfExist('chmod a+rwx,g-w-x,o-wx', '/etc/skel/.bashrc', verbose);
        await execIfExist('chmod a+rwx,g-w-x,o-wx', '/etc/skel/.bash_logout', verbose);
        await execIfExist('chmod a+rwx,g-w-x,o-wx', '/etc/skel/.profile', verbose);
        // quirinux
        let distro = new distro_1.default();
        if (distro.distroId === 'Quirinux') {
            await (0, utils_2.exec)('chmod -R 777 /etc/skel/.config');
            await (0, utils_2.exec)('chmod -R 777 /etc/xdg/autostart'); // here we must change ***
            await (0, utils_2.exec)('chmod -R 777 /home/*/.config');
            await (0, utils_2.exec)('chmod -R 777 /opt/estilos-general/.config');
            await (0, utils_2.exec)('chmod -R 777 /opt/estilos/.config');
            await (0, utils_2.exec)('chmod -R 777 /usr/bin/iniciar-asistente');
            // Copy xfce4-theme-switcher
            await (0, utils_2.exec)('mkdir /etc/skel/.config/xfce4-theme-switcher -p', echo);
            await rsyncIfExist(`/home/${user}/.config/xfce4-theme-switcher`, '/etc/skel/.config/xfce4-theme-switcher', verbose);
        }
        /**
         * ALL Desktops:
         */
        // Emer Chen suggestion
        await rmIfExist('/etc/skel/.config/user-dirs.dirs');
        await rmIfExist('/etc/skel/.config/user-dirs.locale');
        await rmIfExist('/etc/skel/.config/gtk-3.0/bookmarks/', 'r');
        // Manuel Senpai suggestion     
        // await exec(`grep -IE -r /etc/skel -e ${user}`)
        await rmIfExist('/etc/skel/.local/share/recently-used.xbel');
        await rmIfExist('/etc/skel/.config/xfce4/desktop/', 'r');
    }
}
exports.default = Xdg;
/**
 * execIfExist
 * @param cmd
 * @param file
 * @param verbose
 */
async function execIfExist(cmd, file, verbose = false) {
    const echo = utils_1.default.setEcho(verbose);
    if (node_fs_1.default.existsSync(file)) {
        await (0, utils_2.exec)(`${cmd} ${file}`, echo);
    }
}
/**
 *
 */
async function rsyncIfExist(source, dest = '/etc/skel/', verbose = false) {
    const echo = utils_1.default.setEcho(verbose);
    if (node_fs_1.default.existsSync(source)) {
        await (0, utils_2.exec)(`rsync -avx ${source} ${dest}`, echo);
    }
}
/**
 *
 * @param file2Remove
 * @param recursive
 */
async function rmIfExist(file2Remove, recursive = '') {
    if (node_fs_1.default.existsSync(file2Remove)) {
        await (0, utils_2.exec)(`rm -f${recursive} ${file2Remove}`);
    }
}
