#!/usr/bin/env php

<?php

/**
 * Phigrate
 *
 * PHP Version 5.3
 *
 * @category  Phigrate
 * @package   Main
 * @author    Cody Caughlan <codycaughlan % gmail . com>
 * @author    Manuel HERVO <manuel.hervo % gmail .com>
 * @copyright 2007 Cody Caughlan (codycaughlan % gmail . com)
 * @license   GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 * @link      https://github.com/Azema/Phigrate
 *
 * Usage: php main.php [ENV=environment] <task> [task parameters]
 *
 * Options:
 *     -c, --configuration  Path to the configuration file of application.
 *
 *     -d, --database       Path to the configuration file of databases.
 *
 *     -t, --taskdir        Path of the directory of the tasks.
 *
 *     -m, --migrationdir   Path of the directory of the migrations.
 *
 * ###########
 *
 * ENV: The ENV command line parameter can be used to specify a different
 * database to run against, as specific in the configuration file (config/database.inc.php).
 * By default, ENV is "development"
 *
 * task: In a nutshell, task names are pseudo-namespaced. The tasks that come
 * with the framework are namespaced to "db" (e.g. the tasks are "db:migrate", "db:setup", etc).
 * All tasks available actually :
 *
 *      - db:setup : A basic task to initialize your DB for migrations is
 *      available. One should always run this task when first starting out.
 *
 *      - db:migrate : The primary purpose of the framework is to run migrations,
 *      and the execution of migrations is all handled by just a regular ol' task.
 * 
 *      - db:export : The main purpose of the framework is to initiate the migration, 
 *      but you can also export the SQL generated by migration.
 *
 *      - db:version : It is always possible to ask the framework (really the DB)
 *      what version it is currently at.
 *
 *      - db:status : With this taks you'll get an overview of the already
 *      executed migrations and which will be executed when running db:migrate
 *
 *      - db:schema : It can be beneficial to get a dump of the DB in raw SQL
 *      format which represents the current version.
 *
 * For more documentation on the tasks
 * http://blog.phigrate.org/doc/task
 *
 * Call with no arguments to see usage info.
 */

if (strpos('@pear_directory@', '@pear_directory') === 0) {  // not a pear install
    define('PHIGRATE_BASE', realpath(dirname(__FILE__) . '/..'));
} else {
    define('PHIGRATE_BASE', '@pear_directory@/Phigrate');
}
if (strpos('@package_version@', '@package_version') === 0) {  // not a pear install
    define('PHIGRATE_VERSION', '0.9.6');
} else {
    define('PHIGRATE_VERSION', '@package_version@');
}
if (strpos('@package_date@', '@package_date') === 0) {
    define('PHIGRATE_DATE', date('c', mktime(20,12,0,26,11,2012)));
} else {
    define('PHIGRATE_DATE', '@package_date@');
}

set_include_path(
    implode(PATH_SEPARATOR, array(
        PHIGRATE_BASE . '/library',
        get_include_path(),
    ))
);

// PHP_VERSION_ID est disponible depuis PHP 5.2.7, 
// si votre version est antérieure, émulez-le.
if (!defined('PHP_VERSION_ID')) {
   $version = explode('.',PHP_VERSION);

   define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

// DB table where the version info is stored
if (!defined('PHIGRATE_SCHEMA_TBL_NAME')) {
	define('PHIGRATE_SCHEMA_TBL_NAME', 'schema_info');
}

if (!defined('PHIGRATE_TS_SCHEMA_TBL_NAME')) {
	define('PHIGRATE_TS_SCHEMA_TBL_NAME', 'schema_migrations');
}

set_error_handler('scrErrorHandler', E_ALL);
set_exception_handler('scrExceptionHandler');
spl_autoload_register('loader', true, true);

/**
 * Permet d'itérer à reculons sur un répertoire
 * à la recherche d'un fichier de configuration caché
 *
 * @return string
 */
function iterateDir($dir) {
    $fp = opendir($dir);
    while(false !== ($entry = readdir($fp))) {
        if ($entry == '.rucku') {
            closedir($fp);
            return realpath($dir . '/.rucku');
        }
    }
    if (is_dir($dir . '/..') && $dir != '/') {
        closedir($fp);
        return iterateDir(realpath($dir . '/..'));
    }
    closedir($fp);
    return null;
}

// Parse args of command line
if (!isset($argv)) {
    $argv = '';
}

$args = parseArgs($argv);
if (! in_array('-c', $args)) {
    $config = iterateDir(getcwd());
    if (null !== $config) {
        echo 'Fichier de configuration trouvé: ', $config, "\n";
        $args[] = '-c';
        $args[] = $config;
    }
}
$main = new Phigrate_FrameworkRunner($args);
$output = $main->execute();
echo $output, "\n";
// It's good
exit(0);

/**
 * Parse command line arguments
 *
 * @param array $argv Arguments of command line
 *
 * @return array
 */
function parseArgs($argv)
{
    $nbArgs = count($argv);
    if ($nbArgs < 2) {
        printHelp($argv[0]);
    } elseif ($nbArgs == 2) {
        if ($argv[1] == '-h' || $argv[1] == '--help' || $argv[1] == 'help') {
            printHelp($argv[0]);
        }
    }
    return $argv;
}

/**
 * Print a usage scenario for this script.
 * Optionally take a boolean on whether to immediately die or not.
 *
 * @param boolean $exit Flag to die
 *
 * @return void
 */
function printHelp($scriptName)
{
    $version = PHIGRATE_VERSION;
    $dateVersion = PHIGRATE_DATE;
    $usage =<<<USAGE
 ____  _     _                 _
|  _ \| |__ (_) __ _ _ __ __ _| |_ ___
| |_) | '_ \| |/ _` | '__/ _` | __/ _ \
|  __/| | | | | (_| | | | (_| | ||  __/
|_|   |_| |_|_|\__, |_|  \__,_|\__\___|
               |___/

Phigrate v{$version} at {$dateVersion}


Usage: {$scriptName} [options] [ENV=environment] <task> [task parameters]

Options:
    -c, --configuration  Path to the configuration file (INI) of application.

    -d, --database       Path to the configuration file (INI) of databases.

    --force              Force the migration (only for task db:migrate)

    -h, --help           Display this message

    -l, --logdir         Path of the directory of logs.

    -m, --migrationdir   Path of the directory of the migrations.

    -t, --taskdir        Path of the directory of the tasks.

###########

    task --help: Display help of task

    ENV: The ENV command line parameter can be used to specify a different
database to run against, as specific in the configuration file (config/database.inc.php).
By default, ENV is "development"

    task: In a nutshell, task names are pseudo-namespaced. The tasks that come
with the framework are namespaced to "db" (e.g. the tasks are "db:migrate", "db:setup", etc).
All tasks available actually :

     - db:setup : A basic task to initialize your DB for migrations is
     available. One should always run this task when first starting out.

     - db:migrate : The primary purpose of the framework is to run migrations,
     and the execution of migrations is all handled by just a regular ol' task.

     - db:export : The main purpose of the framework is to initiate the migration, 
     but you can also export the SQL generated by migration.

     - db:version : It is always possible to ask the framework (really the DB)
     what version it is currently at.

     - db:status : With this taks you'll get an overview of the already
     executed migrations and which will be executed when running db:migrate

     - db:schema : It can be beneficial to get a dump of the DB in raw SQL
     format which represents the current version.

For more documentation on the tasks, call task with help parameter.
@see http://blog.phigrate.org/doc/task

Call with no arguments to see usage info.


USAGE;
    echo $usage;
    exit(0);
}

/**
 * error_handler
 * Global error handler to process all errors during script execution
 *
 * @param integer $errno   Error number
 * @param string  $errstr  Error message
 * @param string  $errfile Error file
 * @param string  $errline Error line
 *
 * @return void
 */
function scrErrorHandler($errno, $errstr, $errfile, $errline)
{
    echo sprintf(
        "\n\n(%s:%d) %s\n\n",
        basename($errfile),
        $errline,
        $errstr
    );
    exit(1); // exit with error
}

/**
 * exception handler
 * Global exception handler to process all exception during script execution
 *
 * @param Exception $exception Exception
 *
 * @return void
 */
function scrExceptionHandler($exception)
{
    echo 'Error: ', $exception->getMessage(), "\n";
        //. "\nbacktrace: \n" . $exception->getTraceAsString() . "\n";
    exit(1); // exit with error
}

function loader($classname)
{
    $filename = str_replace('_', '/', $classname) . '.php';
    if (defined('PHIGRATE_BASE')
        && is_file(PHIGRATE_BASE . '/library/' . $filename)
    ) {
        $filename = PHIGRATE_BASE . '/library/' . $filename;
    }
    include_once $filename;
}

/* vim: set expandtab tabstop=4 shiftwidth=4: */
