#!/usr/bin/env php
<?php
/**
 * Database migration script.
 *
 * Usage: horde-db-migrate
 *        [--config=filename]
 *        [--debug]
 *        [(application|directory) [(up|down|version)]]
 *
 * Copyright 2010-2013 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL-2). If you
 * did not receive this file, see http://www.horde.org/licenses/lgpl.
 *
 * @author   Chuck Hagenbuch <chuck@horde.org>
 * @author   Jan Schneider <jan@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/lgpl LGPL-2
 * @package  Horde
 */

$baseFile = __DIR__ . '/../lib/Application.php';
if (file_exists($baseFile)) {
    require_once $baseFile;
} else {
    require_once 'PEAR/Config.php';
    require_once PEAR_Config::singleton()
        ->get('horde_dir', null, 'pear.horde.org') . '/lib/Application.php';
}
Horde_Registry::appInit('horde', array(
    'authentication' => 'none',
    'cli' => true
));

// Parse command line arguments.
$parser = new Horde_Argv_Parser(
    array(
        'usage' => "%prog\n\t[--config=filename]\n\t[--debug]\n\t[(application|directory) [(up|down|version)]]",
        'optionList' => array(
            new Horde_Argv_Option(
                '-c',
                '--config',
                array(
                      //'action' => 'store_true',
                    'help'   => 'Path to PEAR configuration file.'
                )
            ),
            new Horde_Argv_Option(
                '-d',
                '--debug',
                array(
                    'action' => 'store_true',
                    'help'   => 'Provide full debugging output.'
                )
            ),
        )
    )
);
list($options, $args) = $parser->parseArgs();

$migration = new Horde_Core_Db_Migration(__DIR__ . '/../..', $options['config']);
if (empty($args[0])) {
    // Run all migrations.
    $apps = $migration->apps;
    $dirs = $migration->dirs;
} else {
    // Run a specific migration.
    $app = $args[0];
    if (($key = array_search($app, $migration->apps)) !== false) {
        $dir = $migration->dirs[$key];
    } elseif (($key = array_search($app, $migration->dirs)) !== false) {
        $dir = $app;
        $app = $migration->apps[$key];
    } else {
        $cli->fatal(
            sprintf(
                '%s is neither a configured Horde application nor a migration directory

Supported applications:

%s

Supported directories:

%s',
                $app,
                join("\n  ", $migration->apps),
                join("\n  ", $migration->dirs)
            )
        );
    }
    $dirs = array($dir);
    $apps = array($app);
}

$action = 'up';
if (!empty($args[1])) {
    switch ($args[1]) {
    case 'up':
    case 'down':
        $action = $args[1];
        break;

    default:
        $action = 'migrate';
        $targetVersion = $args[1];
        break;
    }
}

// Run
$db = $injector->getInstance('Horde_Db_Adapter');
if (!empty($options['debug'])) {
    $logger = new Horde_Log_Logger(new Horde_Log_Handler_Stream(STDOUT));
    $db->setLogger($logger);
}

switch ($action) {
case 'up':
    $cli->message('Migrating DB up.');
    break;

case 'down':
    $cli->message('Migrating DB down.');
    break;

case 'migrate':
    $cli->message('Migrating DB to schema version ' . $targetVersion . '.');
    break;
}

$logger = new Horde_Log_Logger(
    new Horde_Log_Handler_Stream(
        STDOUT, null, new Horde_Log_Formatter_Simple('%message%' . PHP_EOL)));

foreach ($apps as $app) {
    $migrator = $migration->getMigrator($app, $logger);

    $cli->message("Current $app schema version: " . $migrator->getCurrentVersion());

    try {
        switch ($action) {
        case 'up':
            $migrator->up();
            break;

        case 'down':
            $migrator->down();
            break;

        case 'migrate':
            $migrator->migrate($targetVersion);
            break;
        }
    } catch (Exception $e) {
        echo $e->getMessage() . "\n";
        continue;
    }

    $cli->message("Ending $app schema version: " . $migrator->getCurrentVersion());
}
