#!/usr/bin/env php
<?php
define('VERSION', "3.0.1");
define('EOL', PHP_EOL);
define('DS', DIRECTORY_SEPARATOR);

function getParamValue($arguments, $p, $require = false)
{
    foreach ($arguments as $key => $value) {
        if ($value === "-" . $p) {
            $nextKey = $key + 1;
            return isset($arguments[$nextKey]) ? $arguments[$nextKey] : true;
        }
    }

    if ($require === true) {
        throw new Exception("Config file required, see -{$p} param");
    }

    return false;
}

function requireConfigs($arguments)
{
    $configFileParam = getParamValue($arguments, "f", true);
    $configFile = realpath(getcwd() . DS . $configFileParam);

    echo " Config file: " . $configFile . EOL;

    if (!file_exists($configFile)) {
        throw new Exception("Config file not found: " . $configFile);
    }

    return require_once $configFile;
}

echo EOL . " SQL Processor v" . VERSION . " - by Edily Cesar Medule (edilycesar@gmail.com)" . EOL . EOL;

$isHelp = (bool) getParamValue($argv, "h");

if (!$isHelp) {
    $configs = requireConfigs($argv);

    chdir(__DIR__);

    require_once __DIR__ . '/config.php';
//require_once __DIR__ . '/config-' . ENV . '.php';
    require_once __DIR__ . '/src/DbPdoMySql.php';
    require_once __DIR__ . '/src/SqlProcessor.php';

    $sqlProcessor = new SqlProcessor($configs);

    if ($value = getParamValue($argv, "n")) {
        echo "New: " . EOL;
        $sqlProcessor->newQuery();
    }

    if ($author = getParamValue($argv, "a")) {
        $sqlProcessor->setAuthor($author);
    }

    if ($description = getParamValue($argv, "d")) {
        $sqlProcessor->setDescription($description);
    }

    if ($value = getParamValue($argv, "r")) {
        $sqlProcessor->run();
    }

    if ($value = getParamValue($argv, "c")) {
        $sqlProcessor->validateAllLogTables();
    }

    if ($value = getParamValue($argv, "k")) {
        $sqlProcessor->reset();
    }
}

if (1 === (int) $argc || $value = getParamValue($argv, "h")) {

    echo "-n Create file for new query" . EOL;
    echo " - a Define the query author" . EOL;
    echo " - d Define a query description" . EOL;
    echo " - r Run the queries" . EOL;
    echo " - f Config file" . EOL;
    echo " - c Validate runs on all databases" . EOL;
    echo " - h Help" . EOL;
    echo " - m Manual / Documentation (Future)" . EOL;
    echo " - k Clear all, database control table and directory contents" . EOL;
    echo EOL . EOL;
    echo "Example:" . EOL;
    echo " ./cesar-migrator -a Cesar -d Query marotinha -r" . EOL;
}

echo EOL;

