#!/usr/bin/env php
<?php

ini_set('display_errors', 'On');

if (is_file('../../../vendor/autoload.php')) {
    require_once '../../../vendor/autoload.php';
} elseif (is_file('./vendor/autoload.php')) {
    require_once './vendor/autoload.php';
} elseif (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
} else {
    throw new \RuntimeException("Imposible de trouver l'autoload de composer");
}

try {
    $options = new \Console\Options\OptionParser([
        (new \Console\Options\Option('config_file', 'c'))
            ->setType(\Console\Options\Option::T_STRING)
            ->setDefault('./migration-config.json'),
        (new \Console\Options\Option('new', 'n'))
            ->setType(\Console\Options\Option::T_STRING),
        (new \Console\Options\Option('init', 'i'))
            ->setType(\Console\Options\Option::T_FLAG)
    ]);
    $options->parse($argv);

    if ($options['init']) {
        $init = new \Migration\MigrationInit($options['config_file']);
        $init->run();
    } else {
        $config_filename = realpath($options['config_file']) ?: realpath($options[0]);
        if ($config_filename === false) {
            throw new \RuntimeException(
                'Impossible de trouver le fichier de configuration '
                . $options['config_file']
            );
        }
        if (isset($options['new'])) {
            $config = new \Migration\MigrationConfigFile($config_filename);
            $newMigration = new \Migration\CreateMigration($config);
            $newMigration->setNewMigrationName($options['new']);
            $newMigration->run();
        } else {
            $config = new \Migration\MigrationConfigFile($config_filename);
            $migration = new \Migration\Migration($config);
            $migration->run();
        }
    }
} catch (\Throwable $t) {
    echo $t->getMessage() . PHP_EOL;
}