'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

exports.default = parseSSHUrl;

var _isNumber;

function _load_isNumber() {
  return _isNumber = _interopRequireDefault(require('../number/is-number'));
}

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * parse a string representing an SSH url
 * @name parseSSHUrl
 * @param {string} str SSH url to parse
 * @returns
 * @example
 * ```js
 *  parseSSHUrl('ssh://luke@host.com:/usr/lib')
 *  // => { host: 'host.com', username: 'luke', port: 22, path: '/usr/lib' }
 * ```
 *
 * @credit taken from mikeal/sequest and modified
 * to include path and protocol prefix parsing.
 */
function parseSSHUrl(str) {
  var user = 'root';
  var port = 22;
  var path = null;
  if (str.startsWith('ssh://')) str = str.replace('ssh://', '');
  if (str.startsWith('bit://')) str = str.replace('ssh://', '');

  if (str.indexOf('@') !== -1) {
    user = str.slice(0, str.indexOf('@'));
    str = str.slice(str.indexOf('@') + 1);
  }
  if (str.indexOf(':') !== -1) {
    var _str$slice$split = str.slice(str.indexOf(':') + 1).split(':'),
        _str$slice$split2 = _slicedToArray(_str$slice$split, 2),
        potentialPort = _str$slice$split2[0],
        potentialPath = _str$slice$split2[1];

    var maybePort = parseInt(potentialPort);
    if (!Number.isNaN(maybePort) && (0, (_isNumber || _load_isNumber()).default)(maybePort)) {
      port = maybePort;
      if (potentialPath) path = potentialPath;
    }

    if (!potentialPath && Number.isNaN(maybePort)) {
      path = potentialPort;
    }

    str = str.slice(0, str.indexOf(':'));
  }
  var host = str;

  return {
    host,
    path,
    port,
    username: user
  };
}