#!/usr/bin/env node

/**
 * 命令行工具
 *
 * @author Zongmin Lei<leizongmin@gmail.com>
 */

var fs = require('fs');
var path = require('path');
var program = require('commander');
var xss = require('../');
var packageInfo = require('../package.json');

program
  .version(packageInfo.version)
  .option('-t, --test', 'active test')
  .option('-i, --input <input_file>', 'input file name')
  .option('-o, --output <output_file>', 'output filename')
  .option('-c, --config <config_file>', 'load custom config')
  .option('-s, --strip-ignore-tag', 'set stripIgnoreTag=true')
  .option('-b, --strip-ignore-tag-body', 'set stripIgnoreTagBody=true');

program.on('--help', function () {
  console.log('  Examples:');
  console.log('');
  console.log('    $ xss -t');
  console.log('    $ xss -i origin.html');
  console.log('    $ xss -i origin.html -o targer.html');
  console.log('    $ xss -i origin.html -c config.js');
  console.log('    $ xss -i origin.html -s');
  console.log('    $ xss -i origin.html -s -b');
  console.log('');
  console.log('  For more details, please see: https://npmjs.org/package/xss')
});

program.parse(process.argv);

if (program.test) {
  require('../lib/cli');
  return;
}

var config = {};
if (program.config) {
  config = require(path.resolve(program.config));
}
if (program.input) {
  var input = fs.readFileSync(program.input, 'utf8');
} else {
  program.help();
}

if (program['strip-ignore-tag']) {
  config.stripIgnoreTag = true;
}
if (program['strip-ignore-tag-body']) {
  config.stripIgnoreTagBody = true;
}

var output = xss(input, config);

if (program.output) {
  fs.writeFileSync(program.output, output);
} else {
  console.log(output);
}
