#!/usr/bin/env node
"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

var args = require('meow')("\n    Usage\n      $ spark-wallet [options]\n\n    Options\n      -l, --ln-path <path>     path to c-lightning data directory [default: ~/.lightning]\n      -p, --port <port>        http(s) server port [default: 9737]\n      -i, --host <host>        http(s) server listen address [default: localhost]\n      -u, --login <userpwd>    http basic auth login, \"username:password\" format [default: generate random]\n      -C, --cookie-file <path> persist generated login credentials to <path> or load them [default: ~/.spark-wallet/cookie]\n      --no-cookie-file         disable cookie file [default: false]\n\n      --rate-provider <name>   exchange rate provider, one of \"bitstamp\" or \"wasabi\" (requires tor) [default: bitstamp]\n      --no-rates               disable exchange rate lookup [default: false]\n      --proxy <uri>            set a proxy for looking up rates, e.g. socks5h://127.0.0.1:9050 [default: none]\n\n      --force-tls              enable TLS even when binding on localhost [default: enable for non-localhost only]\n      --no-tls                 disable TLS for non-localhost hosts [default: false]\n      --tls-path <path>        directory to read/store key.pem and cert.pem for TLS [default: ~/.spark-wallet/tls/]\n      --tls-name <name>        common name for the TLS cert [default: {host}]\n\n      --letsencrypt <email>    enable CA-signed certificate via LetsEncrypt [default: false]\n      --le-port <port>         port to bind LetsEncrypt verification server [default: 80]\n      --le-noverify            skip starting the LetsEncrypt verification server [default: start when {letsencrypt} is set]\n      --le-debug               display additional debug information for LetsEncrypt [default: false]\n\n      -o, --onion              start Tor Hidden Service (v3) [default: false]\n      -O, --onion-path <path>  directory to read/store hidden service data [default: ~/.spark-wallet/tor/]\n      --onion-nonanonymous     setup hidden service in non-anonymous mode [default: false]\n\n      -k, --print-key          print access key to console (for use with the Cordova/Electron apps) [default: false]\n      -q, --print-qr           print QR code with the server URL [default: false]\n      -Q, --pairing-qr         print QR code with embedded access key [default: false]\n      -P, --pairing-url        print URL with embedded access key [default: false]\n      --public-url <url>       override public URL used for QR codes [default: http(s)://{host}/]\n\n      --allow-cors <origin>    allow browser CORS requests from <origin> (USE WITH CARE) [default: off]\n      --no-webui               run API server without serving client assets [default: false]\n      --no-test-conn           skip testing access to c-lightning rpc (useful for init scripts) [default: false]\n\n      -c, --config <path>      path to config file [default: ~/.spark-wallet/config]\n      -V, --verbose            display debugging information [default: false]\n      -h, --help               output usage information\n      -v, --version            output version number\n\n    Example\n      $ spark-wallet -l ~/.lightning\n\n    All options may also be specified as environment variables:\n      $ LN_PATH=/data/lightning PORT=8070 NO_TLS=1 spark-wallet\n\n", {
  flags: {
    lnPath: {
      alias: 'l'
    },
    login: {
      alias: 'u'
    },
    cookieFile: {
      alias: 'C'
    },
    port: {
      alias: 'p'
    },
    host: {
      alias: 'i'
    },
    leNoverify: {
      type: 'boolean'
    },
    leDebug: {
      type: 'boolean'
    },
    printKey: {
      type: 'boolean',
      alias: 'k'
    },
    printQr: {
      type: 'boolean',
      alias: 'q'
    },
    pairingQr: {
      type: 'boolean',
      alias: 'Q'
    },
    pairingUrl: {
      type: 'boolean',
      alias: 'P'
    },
    onion: {
      type: 'boolean',
      alias: 'o'
    },
    onionPath: {
      alias: 'O'
    },
    onionNonanonymous: {
      type: 'boolean'
    },
    config: {
      alias: 'c'
    },
    verbose: {
      alias: 'V',
      type: 'boolean'
    }
  }
}).flags; // Load config file


var os = require('os'),
    fs = require('fs'),
    path = require('path'),
    ini = require('ini'),
    confPath = args.config || process.env.CONFIG || path.join(os.homedir(), '.spark-wallet', 'config'),
    fileConf = fs.existsSync(confPath) ? ini.parse(fs.readFileSync(confPath, 'utf-8')) : {};

var conf = Object.assign({}, fileConf, args); // Set config options from argv and file as environment variables

Object.keys(conf).filter(function (k) {
  return k.length > 1;
}).map(function (k) {
  return [k.replace(/([^A-Z_])([A-Z])/g, '$1_$2').replace(/-/g, '_').toUpperCase(), conf[k]];
}).forEach(function (_ref) {
  var _ref2 = _slicedToArray(_ref, 2),
      k = _ref2[0],
      v = _ref2[1];

  return v !== false ? process.env[k] = v : process.env["NO_".concat(k)] = true;
}); // Enable cookie file by default in the same dir as the config file

if (!process.env.NO_COOKIE_FILE && !process.env.COOKIE_FILE) process.env.COOKIE_FILE = path.join(os.homedir(), '.spark-wallet', 'cookie');
process.env.NODE_ENV || (process.env.NODE_ENV = 'production');
process.env.VERBOSE && (process.env.DEBUG = "clightning-client,spark,superagent,".concat(process.env.DEBUG || ''));
process.env.ONION_PATH && (process.env.ONION = true); // --onion-path implies --onion

process.env.ONION_NONANONYMOUS && (process.env.ONION = true); // --onion-nonanonymous implies --onion

process.env.PAIRING_QR && (process.env.PRINT_QR = true); // --pairing-qr implies --print-qr

process.env.PROXY && (process.env.ALL_PROXY = process.env.PROXY); // PROXY is an alias for ALL_PROXY

if (process.env.TLS_PATH || process.env.TLS_NAME || process.env.LETSENCRYPT) process.env.FORCE_TLS = true;

require('@babel/polyfill');

require('./app');