module.exports = function generateOrUpdateCert (domain, renew, cb) {
    var console  = require('gifer-console');
    var fs       = require('fs-extra');
    var iconv    = new require('iconv').Iconv('ASCII', 'utf-8');
    var path     = "\"" + MCPathes.LE + "le32.exe\"" +
        " --key mc_account.key --csr mychat.csr --csr-key mc_private.key --crt mc_public.crt --domains " +
        "\"" + domain + "\" " +
        "--path \"" + MCPathes.LeCert + "\" --generate-missing --unlink --live" + (renew ? " --renew 10" : "");
    var le32  = require('child_process').exec(path, {cwd: MCPathes.LeCert});
    var log  = "";
    var _now = new Date().getTime();
    var _key = "mc_private.key";
    var _crt = "mc_public.crt";

    try {
        _now = fs.statSync(MCPathes.LeCert + _crt).ctimeMs;
    } catch (e) {}

    le32.stdout.on('data', function(data) {
        log += data;
    });

    le32.stderr.on('data', function(data) {
        log += data;
    });

    le32.on('exit', function (exitCode) {
        var res = 0;

        try {
            log = iconv.convert(log).toString();
        } catch (e) {}

        try {
            fs.statSync(MCPathes.LeCert + _key);

            try {
                var _stat = fs.statSync(MCPathes.LeCert + _crt);

                if (_stat.ctimeMs < _now){
                    res = 3; // файл mc_public.crt сертификата не обновился
                }
            } catch (e) {
                res = 2; // нет файла mc_public.crt
            }
        } catch (e) {
            res = 1; // нет файла mc_private.key
        }

        if (res === 0) {
            try {
                fs.copySync(MCPathes.LeCert + _crt, MCPathes.Cert + _crt);
                fs.copySync(MCPathes.LeCert + _key, MCPathes.Cert + _key);
            } catch (e) {
                console.immediately(e.message, console.logLevel.FATAL);

                // log = `
                // === Copy log =======================
                // Fail copy from ${MCPathes.LeCert}${_crt} to ${MCPathes.Cert}${_crt}
                // Or
                // Fail copy from ${MCPathes.LeCert}${_key} to ${MCPathes.Cert}${_key}
                // ` + e.message + "\n\n" + log;

                log = "\n" + e.message + "\n\n" + log;
                
                res = 4; // ошибка копирования сертификатов в хранилище
            }
        }

        if (log.indexOf("All verifications failed") > 0) {
            res = 100;
        }

        cb && cb(JSON.stringify({
            Result: res,
            Log : log,
            Code: exitCode,
            Path: path,
            key : _key,
            crt : _crt
        }));

        // console.log('LE32.exe exited with code: ' + code.toString());
    });
};
