#!/usr/bin/env node

/**
 * External dependencies
 */
"use strict";

var _args = _interopRequireDefault(require("args"));

var _opn = _interopRequireDefault(require("opn"));

var _enquirer = require("enquirer");

var _chalk = _interopRequireDefault(require("chalk"));

var _debug = _interopRequireDefault(require("debug"));

var _config = _interopRequireDefault(require("../../config/config.json"));

var _command = _interopRequireDefault(require("../lib/cli/command"));

var _token = _interopRequireDefault(require("../lib/token"));

var _tracker = require("../lib/tracker");

var _rollbar = require("../lib/rollbar");

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

/**
 * Internal dependencies
 */
if (_config.default && _config.default.environment !== 'production') {
  console.log(`${_chalk.default.bgYellow('WARNING:')} RUNNING DEV VERSION OF @automattic/vip`);
  console.log('You should `npm link` your locally checked out copy of this repo as part of your development setup.');
}

const debug = (0, _debug.default)('@automattic/vip:bin:vip'); // Config

const tokenURL = 'https://dashboard.wpvip.com/me/cli/token';

const rootCmd = async function () {
  let token = await _token.default.get();
  const isHelpCommand = process.argv.some(arg => arg === 'help' || arg === '-h' || arg === '--help');
  const isLogoutCommand = process.argv.some(arg => arg === 'logout');
  debug('Argv:', process.argv);

  if (isLogoutCommand || isHelpCommand || token && token.valid()) {
    (0, _command.default)().command('logout', 'Logout from your current session', async () => {
      await _token.default.purge();
      await (0, _tracker.trackEvent)('logout_command_execute');
      console.log('You are successfully logged out.');
    }).command('app', 'List and modify your VIP applications').command('import', 'Check the validity of an import source').command('search-replace', 'Perform Search and Replace tasks on files').command('sync', 'Sync production to a development environment').command('wp', 'Run WP CLI commands against an environment').argv(process.argv);
  } else {
    // Bypass helper function
    _args.default.parse(process.argv);

    console.log();
    console.log('  Welcome to');
    console.log('   _    __ ________         ________    ____');
    console.log('  | |  / //  _/ __ \       / ____/ /   /  _/');
    console.log('  | | / / / // /_/ /______/ /   / /    / /  ');
    console.log('  | |/ /_/ // ____//_____/ /___/ /____/ /   ');
    console.log('  |___//___/_/           \____/_____/___/   ');
    console.log();
    console.log('  VIP CLI is your tool for interacting with and managing your VIP applications.');
    console.log();
    console.log(`  To get started, we need an access token for your VIP account. We'll open ${tokenURL} in your web browser; follow the instructions there to continue.`);
    console.log();
    await (0, _tracker.trackEvent)('login_command_execute');
    const c = await (0, _enquirer.prompt)({
      type: 'confirm',
      name: 'continue',
      message: 'Ready?'
    });

    if (!c.continue) {
      await (0, _tracker.trackEvent)('login_command_browser_cancelled');
      return;
    }

    (0, _opn.default)(tokenURL, {
      wait: false
    });
    await (0, _tracker.trackEvent)('login_command_browser_opened');
    let t = await (0, _enquirer.prompt)({
      type: 'password',
      name: 'token',
      message: 'Access Token:'
    });
    t = t.token;

    try {
      token = new _token.default(t);
    } catch (e) {
      console.log('The token provided is malformed. Please check the token and try again.');

      _rollbar.rollbar.error(e);

      await (0, _tracker.trackEvent)('login_command_token_submit_error', {
        error: e.message
      });
      return;
    }

    if (token.expired()) {
      console.log('The token provided is expired. Please log in again to refresh the token.');
      await (0, _tracker.trackEvent)('login_command_token_submit_error', {
        error: 'expired'
      });
      return;
    }

    if (!token.valid()) {
      console.log('The provided token is not valid. Please log in again to refresh the token.');
      await (0, _tracker.trackEvent)('login_command_token_submit_error', {
        error: 'invalid'
      });
      return;
    }

    try {
      _token.default.set(token.raw);
    } catch (e) {
      await (0, _tracker.trackEvent)('login_command_token_submit_error', {
        error: e.message
      });

      _rollbar.rollbar.error(e);

      throw e;
    } // De-anonymize user for tracking


    await (0, _tracker.aliasUser)(token.id);
    await (0, _tracker.trackEvent)('login_command_token_submit_success'); // Exec the command we originally  wanted

    const argv = process.argv.slice(2);
    debug('Argv', argv);

    if (argv.length) {
      if (!_args.default.isDefined(argv, 'commands')) {
        return _args.default.showHelp();
      }

      return _args.default.runCommand({
        usage: argv
      });
    }

    const {
      spawn
    } = require('child_process');

    spawn(process.argv[0], process.argv.slice(1), {
      stdio: 'inherit'
    });
  }
};

rootCmd();