#!/usr/bin/env php
<?php
require __DIR__ . '/../vendor/autoload.php';

use Clue\Confgen\Factory;
use Clue\Confgen\Executor\NullExecutor;

$args = getopt('t:c:d:h', array('no-scripts'));
$noScripts = array_key_exists('no-scripts', $args);

if (isset($args['h']) || !isset($argv[1])) {
    showUsage();
}

// requires either -t or -c, but not both
if ((!isset($args['t']) && !isset($args['c'])) || isset($args['t'], $argcs['c'])) {
    error('Requires argument for either template ("-t") or configuration ("-c").', 64 /* EX_USAGE */);
}

// JSON input data is optional and defaults to null
$dataFile = isset($args['d']) ? $args['d'] : null;

$executor = null;
if ($noScripts) {
    // We want to skip execution of scripts/commands - use NullExecutor
    $executor = new NullExecutor();
}

$factory = new Factory(null, null, null, $executor);
$confgen = $factory->createConfgen();

try {
    if (isset($args['c'])) {
        $confgen->processDefinition($args['c'], $dataFile);
    } else {
        $confgen->processTemplate($args['t'], $dataFile);
    }
} catch (Twig_Error $e) {
    error('Template error: ' . $e->getMessage(), 1);
} catch (Exception $e) {
    error('Processing failed: ' . $e->getMessage(), $e->getCode());
}

function error($msg, $code = 0)
{
    fwrite(STDERR, 'Error: ' . $msg . PHP_EOL);
    exit($code ? $code : 1);
}

function showUsage()
{
    echo <<<EOT
Configuration file generator (confgen)
Usage: confgen -t template.twig [-d data.json] [--no-scripts]
   Or: confgen -c confgen.json [-d data.json] [--no-scripts]

Options:
    -t            Path to Twig template file
    -c            Path to confgen JSON configuration definition
    -d            Path to optional JSON input data file
    --no-scripts  Skips the execution of the scripts/commands defined by the meta variable "reload"
    -h            Show this help

EOT;
    exit(64 /* EX_USAGE */);
}
