#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    sys = require('util'),
    dust = require('../lib/server'),
    args = process.argv.slice(1),
    name = null;

args = args.filter(function (arg) {
    var match;

    if (match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=([^\s]+))?$/i)) { arg = match[1] }
    else { return arg }

    switch (arg) {
        case 'h':
        case 'help':
            sys.puts("usage: dustc [{-n|--name}=<template_name>] {sourcefilename|-} [destination]");
            process.exit(0);
        case 'n':
        case 'name':
            name = match[2];
            break;
    }
});

var input = args[1];
var output = args[2];
if (output) {
    output = path.resolve(process.cwd(), output);
}

var fd, template;

if (! input) {
    sys.puts("dustc: no input files");
    process.exit(1);
}

var parseDustFile = function (e, data) {
    if (e) {
        sys.puts("dustc: " + e.message);
        process.exit(1);
    }

    template = dust.compile(data, name || input);
    if (output) {
        fd = fs.openSync(output, "w");
        fs.writeSync(fd, template, 0, "utf8");
    } else {
        sys.print(template);
    }
};

if (input != '-') {
    fs.readFile(input, 'utf-8', parseDustFile);
} else {
    process.stdin.resume();
    process.stdin.setEncoding('utf8');

    var buffer = '';
    process.stdin.on('data', function(data) {
        buffer += data;
    });

    process.stdin.on('end', function() {
        parseDustFile(false, buffer);
    });
}
