#!/usr/bin/env php
<?php
/*
* This file is part of pssht.
*
* (c) François Poirotte <clicky@erebot.net>
* Pssht is licensed under the MIT license.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

if (version_compare(phpversion(), '5.3.3', '<')) {
    echo "Pssht requires PHP 5.3.3 or newer." . PHP_EOL;
    exit -1;
}

$extensions = array(
    'ctype',
    'DOM',
    'gmp',
    'openssl',
    'Reflection',
    'sockets',
    'spl',
);

foreach ($extensions as $ext) {
    if (!extension_loaded($ext)) {
        echo "Extension $ext is required" . PHP_EOL;
        exit -1;
    }
}

require_once(
    dirname(__DIR__) .
    DIRECTORY_SEPARATOR . 'vendor' .
    DIRECTORY_SEPARATOR . 'autoload.php'
);

if (!strncasecmp(substr(__FILE__, -5), '.phar', 5)) {
    if (!extension_loaded('phar')) {
        echo "Extension phar is required" . PHP_EOL;
        exit -1;
    }

    try {
        Phar::mapPhar();
    } catch (Exception $e) {
        echo "Cannot process Pssht phar:" . PHP_EOL;
        echo $e->getMessage() . PHP_EOL;
        exit -1;
    }
    $phar       = new Phar(__FILE__);
    $metadata   = $phar->getMetadata();
    define(
        'PSSHT_VERSION',
        isset($metadata['version']) ? $metadata['version'] : 'devel'
    );
} else {
    $path       = dirname(__DIR__) .
        DIRECTORY_SEPARATOR . 'vendor' .
        DIRECTORY_SEPARATOR . 'erebot' .
        DIRECTORY_SEPARATOR . 'buildenv' .
        DIRECTORY_SEPARATOR . 'get_version.php';
    $version    = 'devel';
    if (file_exists($path)) {
        $version = @exec("php " . escapeshellarg($path)) or 'devel';
    }
    define('PSSHT_VERSION', $version);
}

// Load CLI.
class_exists('\\fpoirotte\\Pssht\\CLI');
die(main(isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : 'pssht.xml'));

__HALT_COMPILER();
