#!/usr/bin/env php
<?php
$autoloader = require __DIR__.'/../src/composer_autoload.php';
if (!$autoloader()) {
    die('class autoloader not found.');
}

use Codeages\Plumber\Plumber;

$workDir = getcwd();
$version = '0.7.2';
$commands = ['run', 'start', 'restart', 'stop'];

$usage = sprintf('%s (%s)  [--bootstrap=<file>]', $argv[0], implode('|', $commands));
$doc = <<<DOC
Plumber {$version}

Usage:
  {$usage}

Options:
  -h|--help    show this
  -b <file> --bootstrap=<file>  Load configuration file [default: plumber.php]
DOC;

$args = \Docopt::handle($doc, array('version'=>'Naval Fate 2.0'));

$cmd = null;
foreach($commands as $c) {
    if ($args[$c] === true) {
        $cmd = $c;
        break;
    }
}

$configFile = ($args['--bootstrap'][0] == '/') ? $args['--bootstrap'] : $workDir.'/'.$args['--bootstrap'];
if (!file_exists($configFile)) {
    echo "Error: bootstrap file `{$args['--bootstrap']}` is not exist.";
    exit(1);
}

$config = require $configFile;
if (!$config instanceof \Pimple\Container ) {
    echo "Error: bootstrap file is must return Pimple\Container config object.";
    exit(2);
}

$plumber = new Plumber($config, $configFile);
$plumber->main($cmd);
