"use strict";
/**
 * penguins-eggs
 * lib: cli-autologin.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 fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const utils_1 = tslib_1.__importDefault(require("../classes/utils"));
const pacman_1 = tslib_1.__importDefault(require("../classes/pacman"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
// libraries
const utils_2 = require("../lib/utils");
const startMessage = 'eggs-start-message';
const stopMessage = 'eggs-stop-message';
/*
* Comando per avviare ubiquity:
* sudo --preserve-env DBUS_SESSION_BUS_ADDRESS, XDG_RUNTIME sh -c 'calamares'
*/
/**
 * CliAutologin
 */
class CliAutologin {
    async addAutologin(distro, version, user, userPasswd, rootPasswd, chroot = '/') {
        if (utils_1.default.isSystemd()) {
            /**
             * Systemd
             */
            const fileOverride = `${chroot}/etc/systemd/system/getty@.service.d/override.conf`;
            const dirOverride = path_1.default.dirname(fileOverride);
            if (fs_1.default.existsSync(dirOverride)) {
                shelljs_1.default.exec(`rm ${dirOverride} -rf`);
            }
            shelljs_1.default.exec(`mkdir ${dirOverride}`);
            let content = '';
            content += '[Service]' + '\n';
            content += 'ExecStart=' + '\n';
            content += 'ExecStart=-/sbin/agetty --noclear --autologin ' + user + ' %I $TERM' + '\n';
            fs_1.default.writeFileSync(fileOverride, content);
            shelljs_1.default.exec(`chmod +x ${fileOverride}`);
            await this.addIssue(distro, version, user, userPasswd, rootPasswd, chroot);
            await this.addMotd(distro, version, user, userPasswd, rootPasswd, chroot);
        }
        else if (utils_1.default.isSysvinit()) {
            /**
             * sysvinit
             */
            const inittab = chroot + '/etc/inittab';
            const search = '1:2345:respawn:/sbin/getty';
            // const replace = `1:2345:respawn:/sbin/getty --noclear --autologin ${user} 38400 tty1`
            const replace = `1:2345:respawn:/sbin/getty --autologin ${user} 38400 tty1`;
            let content = '';
            const lines = fs_1.default.readFileSync(inittab, 'utf-8').split('\n');
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].includes(search)) {
                    lines[i] = replace;
                }
                content += lines[i] + '\n';
            }
            fs_1.default.writeFileSync(inittab, content, 'utf-8');
            await this.addIssue(distro, version, user, userPasswd, rootPasswd, chroot);
            await this.addMotd(distro, version, user, userPasswd, rootPasswd, chroot);
        }
    }
    /**
     *
     * @param chroot
     */
    async remove(chroot = '/') {
        if (utils_1.default.isSystemd()) {
            /**
             * Systemd
             */
            const fileOverride = `${chroot}/etc/systemd/system/getty@.service.d/override.conf`;
            const dirOverride = path_1.default.dirname(fileOverride);
            if (fs_1.default.existsSync(dirOverride)) {
                shelljs_1.default.exec(`rm ${dirOverride} -rf`);
            }
            this.msgRemove(`${chroot}/etc/motd`);
            this.msgRemove(`${chroot}/etc/issue`);
        }
        else if (utils_1.default.isSysvinit()) {
            /**
             * sysvinit
             */
            const inittab = chroot + '/etc/inittab';
            const search = '1:2345:respawn:/sbin/getty';
            // const replace = `1:2345:respawn:/sbin/getty --noclear 38400 tty1         `
            const replace = '1:2345:respawn:/sbin/getty 38400 tty1         ';
            let content = '';
            const lines = fs_1.default.readFileSync(inittab, 'utf-8').split('\n');
            for (let i = 0; i < lines.length; i++) {
                if (lines[i].includes(search)) {
                    lines[i] = replace;
                }
                content += lines[i] + '\n';
            }
            fs_1.default.writeFileSync(inittab, content, 'utf-8');
            this.msgRemove(`${chroot}/etc/motd`);
            this.msgRemove(`${chroot}/etc/issue`);
        } // to add: openrc and runit for Devuan
    }
    /**
     *
     * @param distro
     * @param version
     * @param user
     * @param userPasswd
     * @param rootPasswd
     * @param chroot
     */
    async addMotd(distro, version, user, userPasswd, rootPasswd, chroot = '/') {
        const fileMotd = `${chroot}/etc/motd`;
        let installer = 'sudo eggs install';
        if (pacman_1.default.calamaresExists()) {
            if (pacman_1.default.packageIsInstalled('plasma-desktop')) {
                installer = 'startplasma-wayland to run GUI and launch calamares';
            }
            else if (pacman_1.default.packageIsInstalled('xfce4')) {
                installer = 'startxfce4 to run GUI and launch calamares installer';
            }
        }
        if (!fs_1.default.existsSync(fileMotd)) {
            await (0, utils_2.exec)(`touch ${fileMotd}`);
        }
        this.msgRemove(fileMotd);
        let eggsMotd = fs_1.default.readFileSync(fileMotd, 'utf-8');
        eggsMotd += startMessage + '\n';
        eggsMotd += utils_1.default.flag() + '\n';
        eggsMotd += 'You are logged as: ' + chalk_1.default.bold(user) + ' your password is: ' + chalk_1.default.bold(userPasswd) + ', root password: ' + chalk_1.default.bold(rootPasswd) + '\n\n';
        eggsMotd += 'install              : ' + chalk_1.default.bold(installer) + '\n';
        eggsMotd += '  unattended         : ' + chalk_1.default.bold('sudo eggs install --unattended  # us configuration') + '\n';
        eggsMotd += '  unattended custom  : ' + chalk_1.default.bold('sudo eggs install --custom [ br | it | yours ]') + '\n';
        eggsMotd += 'PXE server           : ' + chalk_1.default.bold('sudo eggs cuckoo') + '\n';
        eggsMotd += '(*) to get your custom unattended configuration: fork https://github.com/pieroproietti/penguins-wardrobe' + '\n';
        eggsMotd += '    create your configuration in /config and ask for a Pull Request' + '\n';
        eggsMotd += stopMessage + '\n';
        fs_1.default.writeFileSync(fileMotd, eggsMotd);
    }
    /**
     *
     * @param distro
     * @param version
     * @param user
     * @param userPasswd
     * @param rootPasswd
     * @param chroot
     */
    async addIssue(distro, version, user, userPasswd, rootPasswd, chroot = '/') {
        const fileIssue = `${chroot}/etc/issue`;
        this.msgRemove(fileIssue);
        const eggsIssue = fs_1.default.readFileSync(fileIssue, 'utf-8');
        // eggsIssue += startMessage + '\n'
        // eggsIssue += `This is a ${distro}/${version} system created by Penguins' eggs.\n`
        // eggsIssue += 'You can login with user: ' + chalk.bold(user) + ' and password: ' + chalk.bold(userPasswd) + ', root password: ' + chalk.bold(rootPasswd) + '\n'
        // eggsIssue += stopMessage + '\n'
        fs_1.default.writeFileSync(fileIssue, eggsIssue);
    }
    /**
     *
     * @param path
     */
    async msgRemove(path) {
        if (fs_1.default.existsSync(path)) {
            const rows = fs_1.default.readFileSync(path, 'utf-8').split('\n');
            let cleaned = '';
            let remove = false;
            for (const row of rows) {
                if (row.includes(startMessage)) {
                    remove = true;
                }
                if (!remove && row !== '') {
                    cleaned += row + '\n';
                }
                if (row.includes(stopMessage)) {
                    remove = false;
                }
            }
            fs_1.default.writeFileSync(path, cleaned, 'utf-8');
        }
    }
}
exports.default = CliAutologin;
