#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var program = require('commander');

program
  .version(JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf-8')).version)
  .usage('<javascript>')
  .option('-r, --raw', 'do not attempt to convert data from JSON')
  .option('-u, --ugly', 'ugly output (no indentation)')
  .option('-s, --silent', 'do not print result to standard output')
  .parse(process.argv);

var stdin = "";

if (!process.stdin.isTTY) {
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.on('data', function(chunk) {
    stdin += chunk;
  })
  process.stdin.on('end', start);
} else {
  start();
}

function start() {
  if (!program.raw) {
    // attempt to interpret stdin as JSON
    try {
      stdin = JSON.parse(stdin);
    } catch (e) {
      // ignore
    }
  }
  
  // expose environment variables as globals preceded with $
  for (var name in process.env) {
    var value = process.env[name];

    if (!program.raw) {
      // attempt to interpret variable as JSON
      try {
        value = JSON.parse(value);
      } catch (e) {
        // ignore
      }
    }

    global['$' + name] = value;
  }
    
  var result, output;
  
  try {
    result = output = eval('(' + (program.args.join(' ') || 'undefined') + ')');
  } catch (e) {
    if (e instanceof SyntaxError) {
      result = output = eval(program.args.join(' ') || 'undefined');
    } else {
      throw e;
    }
  }
  
  if (typeof output == 'string') {
    if (output[output.length - 1] != '\n') {
      output = output + '\n';
    }
  } else {
    try {
      if (program.ugly) {
        output = JSON.stringify(output) + '\n';        
      } else {
        output = JSON.stringify(output, null, 2) + '\n';
      }
    } catch (e) {
      // ignore
    }
  }
  
  if (!program.silent) {
    process.stdout.write(output);
  }
  
  process.exit(result ? 0 : 1);
}