#!/usr/bin/env php
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */

use Amf\Application;
use Amf\File;
use Amf\Config;
use Amf\Cli;

use Zend\Code\Reflection\ClassReflection;

function exitcode($message, $code = 1) {
	echo $message;
	exit($code);
}

chdir(dirname(realpath(dirname($_SERVER['argv'][0]))));

require_once "vendor/autoload.php";

Application::bootstrap();
ini_set('html_errors', 0);
$c = Application::get('config');

$app = new Cli\Application($c->name, $c->version);
$app->setCatchExceptions(true);

foreach ($c->plugins as $id => $options) {
	$plugin_options = Application::instance()->pluginOptions($id);
	$plugin_class = $plugin_options->class;

	$reflection = new ClassReflection($plugin_class);
	$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);

	foreach ($methods as $method) {
		$docblock = $method->getDocBlock();
		if (!$docblock)
			continue;

		$tag = $docblock->getTag("command");
		if ($tag === false)
			continue;

		$description = $docblock->getShortDescription();

		$command = new Cli\CommandCallback($tag->getContent());
		if ($description)
			$command->setDescription($description);
		if (method_exists($plugin_class, $method->name.'Setup'))
			call_user_func([$plugin_class, $method->name.'Setup'], $command);
		$command->setCallback([$plugin_class, $method->name]);
		$app->add($command);
	}

	if (method_exists($plugin_class, 'cli'))
		$plugin_class::cli($app, $plugin_options);
}

$app->run();
