#!/usr/bin/env node

'use strict';

const program = require('commander'),
  color = require('colorful'),
  co = require('co'),
  packageInfo = require('../package.json'),
  util = require('../lib/util'),
  rootCACheck = require('./rootCACheck'),
  startServer = require('./startServer'),
  logUtil = require('../lib/log');

program
  .version(packageInfo.version)
  .option('-p, --port [value]', 'proxy port, 8001 for default')
  .option('-w, --web [value]', 'web GUI port, 8002 for default')
  .option('-r, --rule [value]', 'path for rule file,')
  .option('-l, --throttle [value]', 'throttle speed in kb/s (kbyte / sec)')
  .option('-i, --intercept', 'intercept(decrypt) https requests when root CA exists')
  .option('-s, --silent', 'do not print anything into terminal')
  .option('-c, --clear', 'clear all the certificates and temp files')
  .option('--ws-intercept', 'intercept websocket')
  .option('--ignore-unauthorized-ssl', 'ignore all ssl error')
  .parse(process.argv);

if (program.clear) {
  require('../lib/certMgr').clearCerts(() => {
    util.deleteFolderContentsRecursive(util.getAnyProxyPath('cache'));
    console.log(color.green('done !'));
    process.exit(0);
  });
} else if (program.root) {
  require('../lib/certMgr').generateRootCA(() => {
    process.exit(0);
  });
} else {
  co(function *() {
    if (program.silent) {
      logUtil.setPrintStatus(false);
    }

    if (program.intercept) {
      try {
        yield rootCACheck();
      } catch (e) {
        console.error(e);
      }
    }

    return startServer(program);
  })
}

