#!/usr/bin/env php
<?php
// For logging
$stderr = new \SplFileObject('php://stderr', 'w');

try {
	// Dependencies
	require(__DIR__.'/../src/Com/AramisAuto/PHPreprocessor.php');

	// Parse CLI arguments
	// TODO : all this is pretty ugly and has to be reworked
	// TODO : display command usage on error
	$optsParsed = getopt('', array('command:', 'src:', 'properties:', 'exclude-from:', 'merge-with:', 'reverse:'));
	if (!isset($optsParsed['reverse'])) {
		$optsParsed['reverse'] = false;
	} else {
		$optsParsed['reverse'] = $optsParsed['reverse'];
	}

	// Parse command
	$commandsSpec = array(
		'extract' => array('mandatory' => array('src')),
		'apply' => array('mandatory' => array('src', 'properties'))
	);
	if (!isset($optsParsed['command'])) {
		throw new InvalidArgumentException('Please supply a command.');
	}
	$command = $optsParsed['command'];
	unset($optsParsed['command']);
	if (!isset($commandsSpec[$command])) {
		throw new InvalidArgumentException(sprintf('Unknown command "%s"', $command));
	}
	$commandSpec = $commandsSpec[$command];

	// Parse command options
	foreach ($commandSpec['mandatory'] as $option) {
		if (!isset($optsParsed[$option])) {
			throw new InvalidArgumentException(sprintf('Missing option "--%s"', $option));
		}
	}

	// Instanciate preprocessor
	$p = new Com\AramisAuto\PHPreprocessor($stderr);

	// Call appropriate command
	call_user_func(array($p, $command), $optsParsed);
} catch (Exception $e) {
	$stderr->fwrite(sprintf("An error occured : %s\n", $e->getMessage()));
	exit(1);
}

// Exit successfully
exit(0);
