"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.need = need;
exports.system = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));

var system = _interopRequireWildcard(require("./system.js"));

exports.system = system;

var _places = require("./places.js");

var _log = require("./log.js");

var _cloud = require("./cloud.js");

var _build = _interopRequireDefault(require("./build.js"));

var _fsExtra = require("fs-extra");

var _patches = _interopRequireDefault(require("../patches/patches.json"));

var _path = _interopRequireDefault(require("path"));

var _semver = _interopRequireDefault(require("semver"));

var _package = require("../package.json");

var cloud = new _cloud.Cloud({
  owner: 'zeit',
  repo: 'pkg-fetch'
});

function need() {
  return _need.apply(this, arguments);
}

function _need() {
  _need = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
    var opts,
        nodeRange,
        platform,
        arch,
        forceFetch,
        forceBuild,
        dryRun,
        satisfyingNodeVersion,
        nodeVersion,
        fetched,
        built,
        remote,
        fetchFailed,
        _args = arguments;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            satisfyingNodeVersion = function _satisfyingNodeVersio() {
              var versions = Object.keys(_patches.default).filter(function (nv) {
                return _semver.default.satisfies(nv, nodeRange) || nodeRange === 'latest';
              }).sort(function (nv1, nv2) {
                return _semver.default.gt(nv1, nv2) ? 1 : -1;
              });
              return versions.pop();
            };

            opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            // eslint-disable-line complexity
            nodeRange = opts.nodeRange, platform = opts.platform, arch = opts.arch, forceFetch = opts.forceFetch, forceBuild = opts.forceBuild, dryRun = opts.dryRun;

            if (nodeRange) {
              _context.next = 5;
              break;
            }

            throw (0, _log.wasReported)('nodeRange not specified');

          case 5:
            if (platform) {
              _context.next = 7;
              break;
            }

            throw (0, _log.wasReported)('platform not specified');

          case 7:
            if (arch) {
              _context.next = 9;
              break;
            }

            throw (0, _log.wasReported)('arch not specified');

          case 9:
            nodeRange = (0, system.abiToNodeRange)(nodeRange); // 'm48' -> 'node6'

            if ((0, system.isValidNodeRange)(nodeRange)) {
              _context.next = 12;
              break;
            }

            throw (0, _log.wasReported)('nodeRange must start with \'node\'');

          case 12:
            if (nodeRange !== 'latest') {
              nodeRange = 'v' + nodeRange.slice(4); // 'node6' -> 'v6' for semver
            }

            platform = (0, system.toFancyPlatform)(platform); // win32 -> win

            arch = (0, system.toFancyArch)(arch); // ia32 -> x86

            nodeVersion = satisfyingNodeVersion();

            if (nodeVersion) {
              _context.next = 18;
              break;
            }

            throw (0, _log.wasReported)(`No available node version satisfies '${opts.nodeRange}'`);

          case 18:
            fetched = (0, _places.localPlace)({
              from: 'fetched',
              arch,
              nodeVersion,
              platform,
              version: _package.version
            });
            built = (0, _places.localPlace)({
              from: 'built',
              arch,
              nodeVersion,
              platform,
              version: _package.version
            });
            remote = (0, _places.remotePlace)({
              arch,
              nodeVersion,
              platform,
              version: _package.version
            });

            if (forceBuild) {
              _context.next = 28;
              break;
            }

            _context.next = 24;
            return (0, _fsExtra.exists)(fetched);

          case 24:
            if (!_context.sent) {
              _context.next = 28;
              break;
            }

            if (!dryRun) {
              _context.next = 27;
              break;
            }

            return _context.abrupt("return", 'exists');

          case 27:
            return _context.abrupt("return", fetched);

          case 28:
            if (forceFetch) {
              _context.next = 36;
              break;
            }

            _context.next = 31;
            return (0, _fsExtra.exists)(built);

          case 31:
            if (!_context.sent) {
              _context.next = 36;
              break;
            }

            if (!dryRun) {
              _context.next = 34;
              break;
            }

            return _context.abrupt("return", 'exists');

          case 34:
            if (forceBuild) _log.log.info('Reusing base binaries built locally:', built);
            return _context.abrupt("return", built);

          case 36:
            if (forceBuild) {
              _context.next = 44;
              break;
            }

            if (!dryRun) {
              _context.next = 39;
              break;
            }

            return _context.abrupt("return", 'fetched');

          case 39:
            _context.next = 41;
            return cloud.download(remote, fetched);

          case 41:
            if (!_context.sent) {
              _context.next = 43;
              break;
            }

            return _context.abrupt("return", fetched);

          case 43:
            fetchFailed = true;

          case 44:
            if (!dryRun && fetchFailed) {
              _log.log.info('Not found in GitHub releases:', JSON.stringify(remote));
            }

            if (!dryRun) {
              _log.log.info('Building base binary from source:', _path.default.basename(built));
            }

            if (!(system.hostPlatform !== platform)) {
              _context.next = 48;
              break;
            }

            throw (0, _log.wasReported)(`Not able to build for '${opts.platform}' here, only for '${system.hostPlatform}'`);

          case 48:
            if (!(system.hostArch !== arch)) {
              _context.next = 50;
              break;
            }

            throw (0, _log.wasReported)(`Not able to build for '${opts.arch}' here, only for '${system.hostArch}'`);

          case 50:
            if (!(system.knownArchs.indexOf(arch) < 0)) {
              _context.next = 52;
              break;
            }

            throw (0, _log.wasReported)(`Unknown arch '${opts.arch}'. Specify ${system.knownArchs.join(', ')}`);

          case 52:
            if (!dryRun) {
              _context.next = 54;
              break;
            }

            return _context.abrupt("return", 'built');

          case 54:
            _context.next = 56;
            return (0, _build.default)(nodeVersion, arch, built);

          case 56:
            return _context.abrupt("return", built);

          case 57:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _need.apply(this, arguments);
}