#!/usr/bin/env php
<?php declare(strict_types=1);

use ApiClients\Tools\ResourceGenerator\ResourceGenerator;
use function ApiClients\Tools\ResourceGenerator\readYaml;
use function ApiClients\Tools\ResourceGenerator\readYamlDir;

/**
 * Locate and load autoloader
 */
foreach (array(__DIR__ . '/../../autoload.php', __DIR__ . '/vendor/autoload.php') as $file) {
    if (file_exists($file)) {
        require $file;
        break;
    }
}

/**
 * Run application
 */
try {
    if (!isset($argv[1])) {
        throw new Exception('Missing configuration file');
    }

    if (!file_exists($argv[1])) {
        throw new Exception('Passed configuration file doesn\'t exist');
    }

    /**
     * Instance application
     */
    $configuration = [];
    $configuration += readYaml(__DIR__ . DIRECTORY_SEPARATOR . 'generator-settings.yml');
    $configuration += readYaml($argv[1]);
    $configuration['root'] = dirname($argv[1]) . DIRECTORY_SEPARATOR;
    $configuration['files'] = readYamlDir($configuration['root'] . $configuration['yaml_location']);

    (new ResourceGenerator($configuration))->run();
} catch (Exception $e) {
    $message = $e->getMessage();
    echo str_pad(' ', strlen($message)), PHP_EOL;
    echo $message, PHP_EOL;
    echo str_pad(' ', strlen($message)), PHP_EOL;

    echo 'USAGE', PHP_EOL;
    echo "\t" . 'api-client-resource-generator <configuration>', PHP_EOL;
    echo PHP_EOL;
    echo 'EXAMPLE', PHP_EOL;
    echo "\t" . 'api-client-resource-generator ./resources.yaml', PHP_EOL;

    exit(64);
}

exit(0);
