"use strict";

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

var _http = _interopRequireDefault(require("http"));

var _fs = _interopRequireDefault(require("fs"));

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 defaultDir = _path["default"].join(require('os').homedir(), '.spark-wallet', 'tor');

module.exports = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(app) {
    var dir,
        hs_dir,
        httpPort,
        granax,
        torConfig,
        _args = arguments;
    return regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            dir = _args.length > 1 && _args[1] !== undefined ? _args[1] : defaultDir;
            hs_dir = _args.length > 2 && _args[2] !== undefined ? _args[2] : _path["default"].join(dir, 'hidden_service');
            _context.next = 4;
            return new Promise(function (resolve) {
              var httpSrv = _http["default"].createServer(app).listen(0, '127.0.0.1', function (_) {
                return resolve(httpSrv.address().port);
              });
            });

          case 4:
            httpPort = _context.sent;
            _context.next = 7;
            return require('./granax-dep')();

          case 7:
            granax = _context.sent;
            torConfig = {
              DataDirectory: dir,
              HiddenServiceDir: hs_dir,
              HiddenServiceVersion: 3,
              HiddenServicePort: "80 127.0.0.1:".concat(httpPort)
            };

            if (process.env.ONION_NONANONYMOUS) {
              console.log('[warn] Tor Hidden Service configured to run in NON-ANONYMOUS mode. It will provide no privacy.');
              Object.assign(torConfig, {
                SocksPort: 0,
                HiddenServiceNonAnonymousMode: 1,
                HiddenServiceSingleHopMode: 1
              });
            } // Setup an hidden service over the HTTP server


            return _context.abrupt("return", new Promise(function (resolve, reject) {
              return granax({
                authOnConnect: true
              }, [torConfig]).on('error', reject).on('ready', function (_) {
                return resolve("http://".concat(getHost(hs_dir)));
              });
            }));

          case 11:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function (_x) {
    return _ref.apply(this, arguments);
  };
}();

var getHost = function getHost(dir) {
  return _fs["default"].readFileSync(_path["default"].join(dir, 'hostname')).toString().trim();
};