#!/usr/bin/php
<?php

namespace Dbmover;

use Kingconf\Config;
use PDOException;

/**
 * Main dbMover executable.
 */
$start = microtime(true);

if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}

foreach ([
    __DIR__.'/../../autoload.php',
    __DIR__.'/../../vendor/autoload.php',
    __DIR__.'/../vendor/autoload.php',
    __DIR__.'/vendor/autoload.php',
] as $file) {
    if (file_exists($file)) {
        break;
    }
    unset($file);
}

if (!isset($file)) {
    fwrite(STDERR, <<<EOT
\033[1;31mError: \033[0mYou need to set up the project dependencies using the following commands:

\033[1;33mwget http://getcomposer.org/composer.phar
php composer.phar install\033[0m

EOT
    );
    die(1);
}
$autoloader = require $file;

try {
    $config = (object)(array)(new Config(getcwd().'/dbmover.json'));
} catch (Kingconf\Exception $e) {
    fwrite(STDERR, <<<EOT
\033[1;31mError: Config file `dbmover.json` not found or invalid.\033[0m

EOT
    );
    die(1);
}

foreach ($config as $dsn => $settings) {
    preg_match('@^(\w+):@', $dsn, $vendor);
    $vendor = ucfirst(strtolower($vendor[1]));
    $class = "Dbmover\\$vendor";
    if (!class_exists($class)) {
        fwrite(STDOUT, <<<EOT
\033[1;035mNotice:\033[0;37m Vendor `$vendor` is unsupported, skipping.\033[0m

EOT
        );
        continue;
    }
    try {
        $db = new $class($dsn, $settings);
    } catch (PDOException $e) {
        fwrite(STDOUT, <<<EOT
\033[1;035mNotice:\033[0;37m `$dsn` is unavailable on this machine, skipping.\033[0m

EOT
        );
        continue;
    }
    if (!(isset($settings['schema']) && is_array($settings['schema']))) {
        fwrite(STDOUT, <<<EOT
\033[1;035mNotice:\033[0;37m `"schema"` for `$dsn` does not contain an array of file names, skipping.\033[0m

EOT
        );
        continue;
    }
    $any = false;
    foreach ($settings['schema'] as $schema) {
        $work = $schema;
        if ($work{0} != '/') {
            $work = getcwd()."/$work";
        }
        if (!file_exists($work)) {
            fwrite(STDOUT, <<<EOT
\033[1;031mWarning:\033[0;37m `"$schema"` for `$dsn` not found, skipping.\033[0m

EOT
            );
            continue;
        }
        $any = true;
        $db->addSchema(file_get_contents($work));
    }
    if ($any) {
        $db->processSchemas();
    }
}

