#!/usr/bin/env node

/**
 * Marked CLI
 * Copyright (c) 2011-2012, Christopher Jeffrey (MIT License)
 */

var fs = require('fs')
  , util = require('util')
  , marked = require('../');

/**
 * Man Page
 */

var help = function() {
  var spawn = require('child_process').spawn;

  var options = {
    cwd: process.cwd(),
    env: process.env,
    setsid: false,
    customFds: [0, 1, 2]
  };

  spawn('man',
    [__dirname + '/../man/marked.1'],
    options);
};

/**
 * Main
 */

var main = function(argv) {
  var files = []
    , options = {}
    , data = ''
    , input
    , output
    , arg
    , tokens;

  var getarg = function() {
    var arg = argv.shift();
    arg = arg.split('=');
    if (arg.length > 1) {
      argv.unshift(arg.slice(1).join('='));
    }
    return arg[0];
  };

  while (argv.length) {
    arg = getarg();
    switch (arg) {
      case '-o':
      case '--output':
        output = argv.shift();
        break;
      case '-i':
      case '--input':
        input = argv.shift();
        break;
      case '-t':
      case '--tokens':
        tokens = true;
        break;
      case '--gfm':
        options.gfm = true;
        break;
      case '--sanitize':
        options.sanitize = true;
        break;
      case '--pedantic':
        options.pedantic = true;
        break;
      case '-h':
      case '--help':
        return help();
      default:
        files.push(arg);
        break;
    }
  }

  if (!input) {
    if (files.length <= 2) {
      var stdin = process.stdin;

      stdin.setEncoding('utf8');
      stdin.resume();

      stdin.on('data', function(text) {
        data += text;
      });

      stdin.on('end', write);

      return;
    }
    input = files.pop();
  }

  data = fs.readFileSync(input, 'utf8');
  write();

  function write() {
    marked.setOptions(options);

    data = tokens
      ? JSON.stringify(marked.lexer(data), null, 2)
      : marked(data);

    if (!output) {
      process.stdout.write(data + '\n');
    } else {
      fs.writeFileSync(output, data);
    }
  }
};

if (!module.parent) {
  process.title = 'marked';
  main(process.argv.slice());
} else {
  module.exports = main;
}
