import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { getIPAddress, getIPAddressStr } from '../ip/ip.mjs';
import { getChildProcess } from '../nodejs/child_process.mjs';
import { getPath } from '../nodejs/path.mjs';
import { PUBLISH_ENV_MAP, ENV_MAP, PUBLISH_HOST_ENV } from './config.mjs';
import { getPublishRootDir, getPublishBashPath, getPublishModuleName, getPublishEnvValue } from './helper.mjs';
import { postFile } from './post-file.mjs';
import '../nodejs/os.mjs';
import '../env-variable/env-variable.mjs';
import '../nodejs/fs.mjs';
import '../nodejs/http.mjs';

var rootDir = getPublishRootDir();
var PUBLISH_BASH_FILE = getPublishBashPath();
function getDevPwd() {
  var devHostName = getPublishEnvValue(ENV_MAP.DEV_HOST_NAME);
  var devHostPwd = getPublishEnvValue(ENV_MAP.DEV_HOST_PWD);
  return {
    devHostName: devHostName,
    devHostPwd: devHostPwd
  };
}
function validate(_ref) {
  var dir = _ref.dir,
    publishPathProd = _ref.publishPathProd,
    publishPathTest = _ref.publishPathTest,
    publishEnv = _ref.publishEnv;
  if (!dir || typeof dir !== 'string') {
    console.log('[publish] 模块名称不正确，请检查.env.local');
    return 0;
  }
  if (publishEnv === PUBLISH_ENV_MAP.PROD && (!publishPathProd || typeof publishPathProd !== 'string')) {
    console.log('[publish] 正式环境发布路径不正确，请检查.env');
    return 0;
  }
  if (publishEnv === PUBLISH_ENV_MAP.TEST && (!publishPathTest || typeof publishPathTest !== 'string')) {
    console.log('[publish] 测试环境发布路径不正确，请检查.env');
    return 0;
  }
  // 禁止本机发布
  if ((getIPAddress().indexOf('10.45') === 0 || getIPAddress().indexOf('10.20') === 0) && publishEnv === PUBLISH_ENV_MAP.PROD) {
    console.log('[publish] 禁止在本机发布!');
    return 0;
  }
  return true;
}
/**
 * 本地发布模块到测试/生产环境
 * 读取环境变量配置，打包并发布静态资源到指定路径
 * @param {IPublishOptions} options 发布配置选项
 * @param {string} [options.publishEnv='test'] 发布环境，'test' 或 'prod'
 * @param {string} [options.fileTar] 自定义 tar 文件路径
 * @param {string} [options.fileDir] 自定义文件目录路径
 * @returns {Promise<void>}
 * @example
 * ```ts
 * await localPublish({
 *   publishEnv: 'test',
 * });
 * ```
 */
function localPublish(options) {
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var dir, author, publishPathProd, publishPathTest, _options$publishEnv, publishEnv, moduleName, staticDir, tarName, fileSrc, fileAll;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          dir = getPublishEnvValue(ENV_MAP.VUE_APP_DIR);
          author = getPublishEnvValue(ENV_MAP.VUE_APP_AUTHOR);
          publishPathProd = getPublishEnvValue(ENV_MAP.VUE_APP_PATH_PROD);
          publishPathTest = getPublishEnvValue(ENV_MAP.VUE_APP_PATH_TEST);
          _options$publishEnv = options.publishEnv, publishEnv = _options$publishEnv === void 0 ? PUBLISH_ENV_MAP.TEST : _options$publishEnv;
          if (validate({
            dir: dir,
            publishPathProd: publishPathProd,
            publishPathTest: publishPathTest,
            publishEnv: publishEnv
          })) {
            _context.next = 1;
            break;
          }
          return _context.abrupt("return");
        case 1:
          console.log('[publish] 准备发布模块:', dir);
          moduleName = getPublishModuleName(dir);
          staticDir = 'static';
          tarName = "static_".concat(moduleName, "_").concat(getIPAddressStr());
          fileSrc = options.fileTar || getPath().join(rootDir, 'dist', dir, staticDir, "".concat(tarName, ".tar"));
          fileAll = options.fileDir || getPath().join(rootDir, 'dist', dir, staticDir);
          console.log('[publish] moduleName: ', moduleName);
          _context.next = 2;
          return realPublish({
            publishEnv: publishEnv,
            publishPathProd: publishPathProd,
            publishPathTest: publishPathTest,
            moduleName: moduleName,
            fileAll: fileAll,
            fileSrc: fileSrc,
            author: author,
            dir: dir,
            options: options
          });
        case 2:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function realPublish(_ref2) {
  var publishEnv = _ref2.publishEnv,
    publishPathProd = _ref2.publishPathProd,
    publishPathTest = _ref2.publishPathTest,
    moduleName = _ref2.moduleName,
    fileAll = _ref2.fileAll,
    fileSrc = _ref2.fileSrc,
    author = _ref2.author,
    dir = _ref2.dir,
    options = _ref2.options;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var desc, env, shell, _getDevPwd, devHostName, devHostPwd, fileDataInfo, files;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          desc = '';
          env = PUBLISH_HOST_ENV.TEST;
          shell = {};
          shell.runSync = function (cmd, args, options) {
            var shellResult = getChildProcess().spawnSync(cmd, args, options);
            if (shellResult.status !== 0) {
              console.log('[publish] failed: ', shellResult.stderr);
            }
            return shellResult;
          };
          if (!(publishEnv === PUBLISH_ENV_MAP.PROD)) {
            _context2.next = 2;
            break;
          }
          if (!(!publishPathProd || typeof publishPathProd !== 'string')) {
            _context2.next = 1;
            break;
          }
          console.log('[publish] 正式环境发布路径不正确，请检查.env');
          return _context2.abrupt("return");
        case 1:
          desc = "".concat(publishPathProd, "/").concat(moduleName);
          env = PUBLISH_HOST_ENV.PROD;
          _context2.next = 6;
          break;
        case 2:
          if (!(publishEnv === PUBLISH_ENV_MAP.DEV_CLOUD)) {
            _context2.next = 4;
            break;
          }
          _getDevPwd = getDevPwd(), devHostName = _getDevPwd.devHostName, devHostPwd = _getDevPwd.devHostPwd;
          if (!(!devHostName || !devHostPwd)) {
            _context2.next = 3;
            break;
          }
          console.log('[publish] failed: ', "\u6CA1\u6709\u627E\u5230\u6709\u6548\u7684 ".concat(ENV_MAP.DEV_HOST_NAME, " \u6216 ").concat(ENV_MAP.DEV_HOST_PWD));
          return _context2.abrupt("return");
        case 3:
          if (options === null || options === void 0 ? void 0 : options.publishTargetDir) {
            shell.runSync('sh', [PUBLISH_BASH_FILE, fileAll, options.publishTargetDir, devHostName, devHostPwd], {
              stdio: 'inherit'
            });
          } else if (moduleName === 'mobile-official-web') {
            shell.runSync('sh', [PUBLISH_BASH_FILE, fileAll, '/root/html/', devHostName, devHostPwd]);
          } else {
            shell.runSync('sh', [PUBLISH_BASH_FILE, fileAll, "/root/html/".concat(moduleName, "/"), devHostName, devHostPwd], {
              stdio: 'inherit'
            });
          }
          return _context2.abrupt("return");
        case 4:
          if (!(!publishPathTest || typeof publishPathTest !== 'string')) {
            _context2.next = 5;
            break;
          }
          console.log('[publish] 测试环境发布路径不正确，请检查.env');
          return _context2.abrupt("return");
        case 5:
          desc = "".concat(publishPathTest, "/").concat(moduleName);
          env = PUBLISH_HOST_ENV.TEST;
        case 6:
          fileDataInfo = [{
            urlKey: 'src',
            urlValue: fileSrc
          }, {
            urlKey: 'des',
            urlValue: desc
          }, {
            urlKey: 'env',
            urlValue: env
          }, {
            urlKey: 'author',
            urlValue: author || ''
          }];
          console.log('[publish] ', {
            fileDataInfo: fileDataInfo
          });
          files = [{
            urlKey: 'src',
            urlValue: fileSrc
          }];
          _context2.next = 7;
          return postFile(fileDataInfo, files, options).then(function (data) {
            if (data.r == 0) {
              console.log("[\u53D1\u5E03\u6210\u529F]........publish ".concat(dir, " to ").concat(env, " success........\n"));
            } else {
              console.log('[发布失败]', data);
            }
          })["catch"](function (err) {
            console.log('[发布失败]', err);
          });
        case 7:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

export { localPublish, validate };
