"use strict";
/**
 * penguins-eggs
 * class: yolk.ts
 * author: Piero Proietti
 * email: piero.proietti@gmail.com
 * license: MIT
 */
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const utils_1 = tslib_1.__importDefault(require("./utils"));
const pacman_1 = tslib_1.__importDefault(require("./pacman"));
const bleach_1 = tslib_1.__importDefault(require("./bleach"));
const utils_2 = require("../lib/utils");
const shelljs_1 = tslib_1.__importDefault(require("shelljs"));
/**
 *
 */
class Yolk {
    constructor() {
        this.yolkDir = '/var/local/yolk';
        this.verbose = false;
        this.echo = {};
    }
    /**
     *
     */
    async create(verbose = false) {
        this.verbose = verbose;
        this.echo = utils_1.default.setEcho(verbose);
        if (utils_1.default.uefiArch() !== 'amd64') {
            utils_1.default.warning(`yolk is not used on ${utils_1.default.uefiArch()} architecture`);
            return;
        }
        utils_1.default.warning(`Creating yolk on ${this.yolkDir}`);
        utils_1.default.warning('Updating system');
        if (!pacman_1.default.commandIsInstalled('dpkg-scanpackages')) {
            utils_1.default.warning(`I cannot find the command dpkg-scanpackages`);
            process.exit(0);
        }
        let cmd = '';
        try {
            cmd = 'apt-get update --yes';
            await (0, utils_2.exec)(cmd, this.echo);
        }
        catch (error) {
            console.log(error);
            await utils_1.default.pressKeyToExit(cmd);
            process.exit(0);
        }
        if (!this.exists()) {
            await (0, utils_2.exec)(`mkdir ${this.yolkDir} -p`, this.echo);
            await (0, utils_2.exec)(`chown _apt:root ${this.yolkDir} -R`, this.echo);
        }
        else {
            await this.erase();
        }
        // packages we need
        const pkgs = [
            'cryptsetup',
            'grub-efi-amd64',
            'grub-pc',
            'keyutils',
            'shim-signed',
        ];
        process.chdir(this.yolkDir);
        utils_1.default.warning(`Downloading packages and its dependencies`);
        for (const pkg of pkgs) {
            utils_1.default.warning(`- ${pkg}`);
            cmd = `apt-cache depends --recurse --no-recommends --no-suggests --no-conflicts --no-breaks --no-replaces --no-enhances ${pkg} | grep "^\\w" | sort -u`;
            let depends = pkg + '\n';
            depends += (await (0, utils_2.exec)(cmd, { echo: false, capture: true })).data;
            await this.installDeps(depends.split('\n'));
        }
        // create Package.gz
        cmd = 'dpkg-scanpackages -h  md5,sha1,sha256 . | gzip -c > Packages.gz';
        utils_1.default.warning(cmd);
        await (0, utils_2.exec)(cmd, { echo: false, capture: true });
        // Create Release date: Sat, 14 Aug 2021 07:42:00 UTC
        const now = shelljs_1.default.exec('date -R -u').stdout.trim();
        const content = `Archive: stable\nComponent: yolk\nOrigin: penguins-eggs\nArchitecture: ${utils_1.default.uefiArch()} \nDate: ${now}\n`;
        utils_1.default.warning('Writing Release');
        fs_1.default.writeFileSync('Release', content);
        // Cleaning
        utils_1.default.warning('Cleaning apt cache');
        const bleach = new bleach_1.default();
        await bleach.clean(verbose);
    }
    /**
     * if depends are not Installed
     * download depends
     * @param depends
     */
    async installDeps(depends) {
        // select for downloads only packages NOT already installed
        const toDownloads = [];
        for (const depend of depends) {
            // if (depend !== '' && !Pacman.packageIsInstalled(depend)) {
            toDownloads.push(depend);
            // }
        }
        // now we go to downloads them
        for (const toDownload of toDownloads) {
            process.chdir(this.yolkDir);
            const cmd = `apt-get download ${toDownload}`;
            // Utils.warning(`- ${cmd}`)
            await (0, utils_2.exec)(cmd, this.echo);
        }
    }
    /**
    * Check if yoil exists and it's a repo
    */
    exists() {
        const check = `${this.yolkDir}/Packages.gz`;
        return fs_1.default.existsSync(check);
    }
    /**
     * Svuota la repo yolk
     */
    async erase() {
        await (0, utils_2.exec)(`rm ${this.yolkDir}/*`, this.echo);
    }
}
exports.default = Yolk;
