"use strict";
/**
 * penguins-eggs
 * class: settings.ts
 * author: Piero Proietti
 * email: piero.proietti@gmail.com
 * license: MIT
 */
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
// packages
const node_fs_1 = tslib_1.__importDefault(require("node:fs"));
const node_os_1 = tslib_1.__importDefault(require("node:os"));
const js_yaml_1 = tslib_1.__importDefault(require("js-yaml"));
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const pjson = require('../../package.json');
// classes
const utils_1 = tslib_1.__importDefault(require("./utils"));
const distro_1 = tslib_1.__importDefault(require("./distro"));
const pacman_1 = tslib_1.__importDefault(require("./pacman"));
const config_file = '/etc/penguins-eggs.d/eggs.yaml';
/**
 * Setting
 */
class Settings {
    constructor(compression = '') {
        this.app = {};
        this.config = {};
        this.remix = {};
        this.work_dir = {};
        this.distro = {};
        this.incubator = {};
        this.i686 = false;
        this.isLive = false;
        this.efi_work = '';
        this.iso_work = '';
        this.kernel_image = '';
        this.initrd_image = '';
        this.vmlinuz = '';
        this.initrdImg = '';
        this.session_excludes = '';
        this.isoFilename = ''; // resulting name of the iso
        this.config.compression = compression;
        this.app.author = 'Piero Proietti';
        this.app.homepage = 'https://github.com/pieroproietti/penguins-eggs';
        this.app.mail = 'piero.proietti@gmail.com';
        this.app.name = pjson.name;
        this.app.version = pjson.version;
        this.isLive = utils_1.default.isLive();
        this.i686 = utils_1.default.isi686();
        this.distro = new distro_1.default(this.remix);
    }
    /**
     *
     * @param config
     */
    async save(config) {
        node_fs_1.default.writeFileSync(config_file, js_yaml_1.default.dump(config), 'utf-8');
    }
    /**
     * Load configuration from config_file
     * @returns {boolean} Success
     */
    async load() {
        const foundSettings = true;
        if (!node_fs_1.default.existsSync(config_file)) {
            console.log(`cannot find configuration file ${config_file},`);
            console.log('please generate it with: sudo eggs config');
            process.exit(1);
        }
        this.config = js_yaml_1.default.load(node_fs_1.default.readFileSync(config_file, 'utf-8'));
        this.session_excludes = '';
        if (!this.config.snapshot_dir.endsWith('/')) {
            this.config.snapshot_dir += '/';
        }
        this.work_dir.ovarium = this.config.snapshot_dir + 'ovarium/';
        // hidden .mnt under nest
        this.config.snapshot_mnt = this.config.snapshot_dir + '.mnt/';
        if (!this.config.snapshot_mnt.endsWith('/')) {
            this.config.snapshot_mnt += '/';
        }
        // hidden .overlay under nest was under ovarium
        this.work_dir.lowerdir = this.config.snapshot_dir + '.overlay/lowerdir';
        this.work_dir.upperdir = this.config.snapshot_dir + '.overlay/upperdir';
        this.work_dir.workdir = this.config.snapshot_dir + '.overlay/workdir';
        this.work_dir.merged = this.config.snapshot_mnt + 'filesystem.squashfs';
        this.efi_work = this.config.snapshot_mnt + 'efi-work/';
        this.iso_work = this.config.snapshot_mnt + 'iso/';
        // remember: before was hostname, not empty
        if (this.config.snapshot_basename === '') {
            this.config.snapshot_basename = node_os_1.default.hostname();
        }
        if (this.config.make_efi && !pacman_1.default.isUefi()) {
            if (utils_1.default.uefiArch() === 'amd64') {
                utils_1.default.error('You choose to create an UEFI image, but miss to install grub-efi-amd64-bin package.');
                utils_1.default.error('Please install it before to create an UEFI image:');
                utils_1.default.warning('sudo apt install grub-efi-amd64-bin');
                utils_1.default.error('or edit /etc/penguins-eggs.d/eggs.yaml and set the valuer of make_efi = false');
                this.config.make_efi = false;
            }
        }
        this.kernel_image = this.config.vmlinuz;
        this.initrd_image = this.config.initrd_img;
        this.vmlinuz = this.kernel_image.slice(this.kernel_image.lastIndexOf('/'));
        this.initrdImg = this.initrd_image.slice(this.initrd_image.lastIndexOf('/'));
        /**
         * Use the login name set in the config file. If not set, use the primary
         * user's name. If the name is not "user" then add boot option. ALso use
         * the same username for cleaning geany history.
         */
        if ((this.config.user_opt === undefined || this.config.user_opt === '') && // this.user_opt = shx.exec('awk -F":" \'/1000:1000/ { print $1 }\' /etc/passwd', { silent: true }).stdout.trim()
            this.config.user_opt === '') {
            this.config.user_opt = 'live';
        }
        if (this.config.user_opt_passwd === '') {
            this.config.user_opt_passwd = 'evolution';
        }
        if (this.config.root_passwd === '') {
            this.config.root_passwd = 'evolution';
        }
        if (this.config.timezone === undefined || this.config.timezone === '') {
            this.config.timezone = shelljs_1.default.exec('cat /etc/timezone', { silent: true }).stdout.trim();
        }
        return foundSettings;
    }
    /**
     * Calculate and show free space on the disk
     * @returns {void}
     */
    async listFreeSpace() {
        if (!node_fs_1.default.existsSync(this.config.snapshot_dir)) {
            node_fs_1.default.mkdirSync(this.config.snapshot_dir);
            if (!node_fs_1.default.existsSync(this.config.snapshot_mnt)) {
                node_fs_1.default.mkdirSync(this.config.snapshot_mnt);
            }
        }
        /** Lo spazio usato da SquashFS non è stimabile da live
         * errore buffer troppo piccolo
         */
        const gb = 1048576;
        let spaceAvailable = 0;
        if (!utils_1.default.isLive()) {
            console.log(`Disk space used: ${Math.round((utils_1.default.getUsedSpace() / gb) * 10) / 10} GB`);
        }
        spaceAvailable = Number(shelljs_1.default
            .exec(`df "${this.config.snapshot_mnt}" | /usr/bin/awk 'NR==2 {print $4}'`, {
            silent: true,
        })
            .stdout.trim());
        console.log(`Space available: ${Math.round((spaceAvailable / gb) * 10) / 10} GB`);
        console.log(`There are ${utils_1.default.getSnapshotCount(this.config.snapshot_mnt)} snapshots taking ${Math.round((utils_1.default.getSnapshotSize(this.config.snapshot_mnt) / gb) * 10) / 10} GB of disk space.`);
        console.log();
        if (spaceAvailable > gb * 3) {
            console.log(chalk_1.default.cyanBright('The free space should be sufficient to hold the'));
            console.log(chalk_1.default.cyanBright('compressed data from the system'));
        }
        else {
            console.log(chalk_1.default.redBright('The free space should be insufficient') + '.');
            console.log();
            if (utils_1.default.isMountpoint(this.config.snapshot_mnt)) {
                console.log('If necessary, you can create more available space');
                console.log('by removing previous  snapshots and saved copies.');
            }
            else {
                console.log(`You can mount a free partition under ${this.config.snapshot_mnt}`);
            }
            console.log();
        }
    }
    /**
     *
     * @param basename
     * @param theme
     */
    async loadRemix(basename = '', theme = '') {
        this.remix.versionNumber = utils_1.default.getPackageVersion();
        this.remix.kernel = utils_1.default.kernelVersion();
        this.remix.branding = theme === '' ? 'eggs' : this.remix.branding = theme.slice(Math.max(0, theme.lastIndexOf('/') + 1));
        this.remix.name = this.config.snapshot_basename;
        let name = this.config.snapshot_prefix + this.config.snapshot_basename;
        name = name.replace(/-/g, ' ').replace(/_/g, ' ').replace('egg of ', '');
        this.remix.fullname = name;
        this.remix.versionName = name.toUpperCase();
    }
}
exports.default = Settings;
