#!/usr/bin/env php
<?php
$autoloadPath = null;
$autoloadPaths = array(
	__DIR__ . '/../../../autoload.php',
	__DIR__ . '/../../vendor/autoload.php',
	__DIR__ . '/../vendor/autoload.php'
);

foreach ($autoloadPaths as $file) {
	if (file_exists($file)) {
		$autoloadPath = $file;
		include($autoloadPath);
		break;
	}
}

if (is_null($autoloadPath)) {
	fwrite(
		STDERR,
		'You need to set up the project dependencies using Composer:' . PHP_EOL . PHP_EOL .
			'    composer install' . PHP_EOL . PHP_EOL .
			'You can learn all about Composer on https://getcomposer.org/.' . PHP_EOL
	);
	die(1);
}

define('BASE_FOLDER', dirname(dirname(dirname(__DIR__))));

$show_config_file_template = false;
if (array_key_exists(1, $argv)) {
	$configfile = $argv[1];

	if (!file_exists($configfile)) {
		fwrite(
			STDERR,
			'Config file does not exist.' . PHP_EOL . PHP_EOL
		);
		$show_config_file_template = true;
	}
} else {
	fwrite(
		STDERR,
		'Please specify a config file.' . PHP_EOL . PHP_EOL
	);
	$show_config_file_template = true;
}

if ($show_config_file_template) {
	fwrite(
		STDERR,
		'Create a file with the contents like:' . PHP_EOL . PHP_EOL . file_get_contents(__DIR__ . '/../tests/testdb2modelconf.php')
	);

	die(1);
}
// Configuration defaults
$db_host = 'localhost';
$db_port = 3306;
$db_name = '';
$db_username = '';
$db_password = '';
$models_output_dir = __DIR__ . '/Auto';
$model_to_extend = '\MyApp\ORMBaseClass';
$controller_model_to_extend = '\Auto\Controller';
$use_namespaces = false;
$namespace_prefixes = [];
$default_namespace = 'MyApp';
$plural_tables = [];

// Override from local config file
include($configfile);

\Granada\ORM::configure('mysql:host=' . $db_host . ';port=' . $db_port . ';dbname=' . $db_name);
\Granada\ORM::configure('username', $db_username);
\Granada\ORM::configure('password', $db_password);

\Granada\Builder\Autobuild::doBuild($models_output_dir, $model_to_extend, $controller_model_to_extend, $use_namespaces, $namespace_prefixes, $default_namespace, $plural_tables);
