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

declare(strict_types=1);

use BillingManager\Console\CreateAdminCommand;
use BillingManager\Console\InstallCommand;
use BillingManager\Console\MigrateCommand;
use BillingManager\Console\PipeCommand;
use BillingManager\Console\QueueWorkCommand;
use BillingManager\Console\ResetAdminTotpCommand;
use BillingManager\Console\WhmcsMigrateCommand;
use BillingManager\Core\Services;
use BillingManager\Core\Version;
use BillingManager\Database\Migrator;
use Symfony\Component\Console\Application;

if (PHP_SAPI !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
if (!is_file($root . '/vendor/autoload.php')) {
    fwrite(STDERR, "Dependencies are missing. Run `composer install` in {$root}\n");
    exit(1);
}

// Before installation there is no configuration.php: only the installer is available.
if (!is_file($root . '/configuration.php')) {
    require $root . '/vendor/autoload.php';
    $app = new Application('HostBMS (not installed)', Version::VERSION);
    $app->add(new InstallCommand($root));
    $app->run();
    exit;
}

require $root . '/init.php';

$app = new Application('HostBMS', Version::VERSION);
$app->add(new MigrateCommand(Migrator::forConnection($capsule->getConnection(), BM_ROOT . '/database/migrations')));
$app->add(new CreateAdminCommand(Services::adminAuth($config)));
$app->add(new ResetAdminTotpCommand(Services::adminAuth($config)));
$app->add(new QueueWorkCommand());
$app->add(new PipeCommand());
$app->add(new InstallCommand(BM_ROOT));
$app->add(new WhmcsMigrateCommand());
$app->run();
