"use strict";

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

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

function _isNumber() {
  const data = _interopRequireDefault(require("../number/is-number"));

  _isNumber = function () {
    return data;
  };

  return data;
}

/**
 * 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) {
  let user = 'root';
  let port = 22;
  let 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) {
    const [potentialPort, potentialPath] = str.slice(str.indexOf(':') + 1).split(':');
    const maybePort = parseInt(potentialPort);

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

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

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

  const host = str;
  return {
    host,
    path,
    port,
    username: user
  };
}