"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.taskRnvCryptoDecrypt = exports["default"] = void 0;var _path = _interopRequireDefault(require("path"));
var _tar = _interopRequireDefault(require("tar"));
var _logger = require("../../core/systemManager/logger");





var _fileutils = require("../../core/systemManager/fileutils");








var _prompt = require("../../cli/prompt");
var _crypto = require("../../core/systemManager/crypto");
var _taskManager = require("../../core/taskManager");
var _constants = require("../../core/constants");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { "default": obj };}function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {Promise.resolve(value).then(_next, _throw);}}function _asyncToGenerator(fn) {return function () {var self = this,args = arguments;return new Promise(function (resolve, reject) {var gen = fn.apply(self, args);function _next(value) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);}function _throw(err) {asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);}_next(undefined);});};}


var iocane = require('iocane');

var _unzipAndCopy = /*#__PURE__*/function () {var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(
  c,
  shouldCleanFolder,
  destTemp,
  wsPath,
  ts,
  destFolder) {return regeneratorRuntime.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:if (!

            shouldCleanFolder) {_context.next = 3;break;}_context.next = 3;return (
              (0, _fileutils.cleanFolder)(wsPath));case 3:_context.next = 5;return (


              _tar["default"].x({
                file: destTemp,
                cwd: c.paths.workspace.dir }));case 5:


            (0, _fileutils.removeFilesSync)([destTemp]);
            if ((0, _fileutils.fsExistsSync)(ts)) {
              (0, _fileutils.copyFileSync)(
              ts,
              _path["default"].join(
              c.paths.workspace.dir,
              c.files.project["package"].name,
              'timestamp'));


            }
            (0, _logger.logSuccess)("Files succesfully extracted into ".concat(destFolder));case 8:case "end":return _context.stop();}}}, _callee);}));return function _unzipAndCopy(_x, _x2, _x3, _x4, _x5, _x6) {return _ref.apply(this, arguments);};}();


var taskRnvCryptoDecrypt = /*#__PURE__*/function () {var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(c, parentTask, originTask) {var _c$files$project$conf, _c$files$project$conf2, _c$files$project$conf3;var sourceRaw, source, ts, destFolder, destTemp, envVar, shouldCleanFolder, wsPath, isCryptoReset, options, _yield$inquirerPrompt, option, _yield$inquirerPrompt2, confirm, key, data, _e$message, err;return regeneratorRuntime.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
            (0, _logger.logTask)('taskRnvCryptoDecrypt');if (

            parentTask) {_context2.next = 4;break;}_context2.next = 4;return (
              (0, _taskManager.executeTask)(c, _constants.TASK_PROJECT_CONFIGURE, _constants.TASK_CRYPTO_DECRYPT, originTask));case 4:


            sourceRaw = (_c$files$project$conf = c.files.project.config) === null || _c$files$project$conf === void 0 ? void 0 : (_c$files$project$conf2 = _c$files$project$conf.crypto) === null || _c$files$project$conf2 === void 0 ? void 0 : (_c$files$project$conf3 = _c$files$project$conf2.decrypt) === null || _c$files$project$conf3 === void 0 ? void 0 : _c$files$project$conf3.source;if (!

            sourceRaw) {_context2.next = 63;break;}
            source = "".concat((0, _fileutils.getRealPath)(c, sourceRaw, 'decrypt.source'));
            ts = "".concat(source, ".timestamp");
            destFolder = _path["default"].join(
            c.paths.workspace.dir,
            c.files.project["package"].name);

            destTemp = "".concat(_path["default"].join(
            c.paths.workspace.dir,
            c.files.project["package"].name.replace('/', '-')), ".tgz");

            envVar = (0, _crypto.getEnvVar)(c);
            shouldCleanFolder = false;
            wsPath = _path["default"].join(
            c.paths.workspace.dir,
            c.files.project["package"].name);

            isCryptoReset = c.command === 'crypto' && c.program.reset === true;if (!(

            c.program.ci !== true && !isCryptoReset)) {_context2.next = 28;break;}
            options = [
            'Yes - override (recommended)',
            'Yes - merge',
            'Skip'];_context2.next = 18;return (

              (0, _prompt.inquirerPrompt)({
                name: 'option',
                type: 'list',
                choices: options,
                message: "How to decrypt to ".concat((0, _logger.chalk)().white(destFolder), " ?") }));case 18:_yield$inquirerPrompt = _context2.sent;option = _yield$inquirerPrompt.option;if (!(

            option === options[0])) {_context2.next = 24;break;}
            shouldCleanFolder = true;_context2.next = 26;break;case 24:if (!(
            option === options[2])) {_context2.next = 26;break;}return _context2.abrupt("return",
            true);case 26:_context2.next = 29;break;case 28:


            shouldCleanFolder = true;case 29:if (!


            (0, _fileutils.fsExistsSync)(destTemp)) {_context2.next = 38;break;}_context2.next = 32;return (
              (0, _prompt.inquirerPrompt)({
                type: 'confirm',
                message: "Found existing decrypted file at ".concat((0, _logger.chalk)().white(
                destTemp), ". want to use it and skip decrypt ?") }));case 32:_yield$inquirerPrompt2 = _context2.sent;confirm = _yield$inquirerPrompt2.confirm;if (!


            confirm) {_context2.next = 38;break;}_context2.next = 37;return (
              _unzipAndCopy(
              c,
              shouldCleanFolder,
              destTemp,
              wsPath,
              ts,
              destFolder));case 37:return _context2.abrupt("return",

            true);case 38:



            key = c.program.key || c.process.env[envVar];if (
            key) {_context2.next = 41;break;}return _context2.abrupt("return",
            Promise.reject("encrypt: You must pass ".concat((0, _logger.chalk)().white(
            '--key'), " or have env var defined:\n\n").concat(


            (0, _crypto.getEnvExportCmd)(envVar, 'REPLACE_WITH_ENV_VARIABLE'), "\n\n")));case 41:if (



            (0, _fileutils.fsExistsSync)(source)) {_context2.next = 43;break;}return _context2.abrupt("return",
            Promise.reject("Can't decrypt. ".concat(
            (0, _logger.chalk)().white(source), " is missing!")));case 43:_context2.prev = 43;_context2.next = 46;return (





              iocane.createSession().
              use('cbc').
              decrypt((0, _fileutils.fsReadFileSync)(source), key));case 46:data = _context2.sent;_context2.next = 58;break;case 49:_context2.prev = 49;_context2.t0 = _context2["catch"](43);if (!(_context2.t0 !== null && _context2.t0 !== void 0 && (_e$message =

            _context2.t0.message) !== null && _e$message !== void 0 && _e$message.includes)) {_context2.next = 57;break;}if (!
            _context2.t0.message.includes('Signature mismatch')) {_context2.next = 55;break;}
            err = "You're trying to decode crypto file encoded with previous version of crypto.\nthis change was introduced in \"rnv@0.29.0\"\n\n".concat(_context2.t0, "\n\n      ").concat(




            (0, _logger.chalk)().green('SUGGESTION:'), "\n\n      ").concat(

            (0, _logger.chalk)().yellow('STEP 1:'), "\n      run: ").concat(
            (0, _logger.chalk)().white('rnv crypto encrypt'), " locally at least once and commit the result back to your repository\n\n      ").concat(

            (0, _logger.chalk)().yellow('STEP 2:'), "\n      you should be able to use: ").concat(
            (0, _logger.chalk)().white('rnv crypto decrypt'), " properly now\n\n      ").concat(

            (0, _logger.chalk)().yellow('IF ALL HOPE IS LOST:'), "\n      Raise new issue and copy this SUMMARY box output at:\n      ").concat(

            (0, _logger.chalk)().white('https://github.com/renative-org/renative/issues'), "\n      and we will try to help!\n\n      ");return _context2.abrupt("return",




            Promise.reject(err));case 55:if (!
            _context2.t0.message.includes('Authentication failed')) {_context2.next = 57;break;}return _context2.abrupt("return",
            Promise.reject("It seems like you provided invalid decryption key.\n\n".concat(

            _context2.t0.stack, "\n\n").concat(

            (0, _logger.chalk)().green('SUGGESTION:'), "\n\n").concat(

            (0, _logger.chalk)().yellow('STEP 1:'), "\ncheck if your ENV VAR is correct: ").concat(
            (0, _crypto.getEnvExportCmd)(envVar, '***********'), "\nor if someone did not encrypt ").concat(
            (0, _logger.chalk)().white(source), " with a different key\n\n").concat(

            (0, _logger.chalk)().yellow('STEP 2:'), "\nrun crypto decrypt again\n\n").concat(


            (0, _logger.chalk)().yellow('IF ALL HOPE IS LOST:'), "\nRaise new issue and copy this SUMMARY box output at:\n").concat(

            (0, _logger.chalk)().white('https://github.com/renative-org/renative/issues'), "\nand we will try to help!\n\n")));case 57:return _context2.abrupt("return",






            Promise.reject(_context2.t0));case 58:



            (0, _fileutils.fsWriteFileSync)(destTemp, data);

            //         try {
            //             await executeAsync(
            //                 c,
            //                 `${_getOpenSllPath(
            //                     c
            //                 )} enc -aes-256-cbc -md md5 -d -in ${source} -out ${destTemp} -k ${key}`,
            //                 { privateParams: [key] }
            //             );
            //         } catch (e) {
            //             const cmd1 = chalk().white(
            //                 `openssl enc -aes-256-cbc -md md5 -d -in ${source} -out ${destTemp} -k $${envVar}`
            //             );
            //             return Promise.reject(`${e}

            // ${chalk().green('SUGGESTION:')}

            // ${chalk().yellow('STEP 1:')}
            // ${cmd1}

            // ${chalk().yellow('STEP 2:')}
            // ${chalk().white(
            //         'run your previous command again and choose to skip openssl once asked'
            //     )}`);
            //         }
            _context2.next = 61;return (
              _unzipAndCopy(
              c,
              shouldCleanFolder,
              destTemp,
              wsPath,
              ts,
              destFolder));case 61:_context2.next = 65;break;case 63:


            (0, _logger.logWarning)("You don't have {{ crypto.encrypt.dest }} specificed in ".concat(
            (0, _logger.chalk)().white(
            c.paths.appConfigBase)));return _context2.abrupt("return",


            true);case 65:case "end":return _context2.stop();}}}, _callee2, null, [[43, 49]]);}));return function taskRnvCryptoDecrypt(_x7, _x8, _x9) {return _ref2.apply(this, arguments);};}();exports.taskRnvCryptoDecrypt = taskRnvCryptoDecrypt;var _default =



{
  description: 'Decrypt encrypted project files into local ~/<wokspace>/<project>/..',
  fn: taskRnvCryptoDecrypt,
  task: _constants.TASK_CRYPTO_DECRYPT,
  params: _constants.PARAMS.withBase(),
  platforms: [],
  skipPlatforms: true };exports["default"] = _default;
//# sourceMappingURL=task.rnv.crypto.decrypt.js.map