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

require_once('vendor/autoload.php');
require_once('utils.inc.php');

use PhpDevCommunity\DotEnv;
use League\CLImate\CLImate;

$climate = new CLImate();
$climate->description('yeswiki-remover, remove a domain used for YesWiki because death is not the end 💀😈');

if (0 == posix_getuid()) {
    $absolutePathToEnvFile = __DIR__ . '/.env';
    if (file_exists($absolutePathToEnvFile)) {
        (new DotEnv($absolutePathToEnvFile))->load();
    } else {
        $climate->error('ERROR : No .env file found.');
        exit;
    }

    $climate->arguments->add([
        'domain' => [
            'prefix'       => 'd',
            'longPrefix'   => 'domain',
            'description'  => 'Domain name that will be removed',
            'required'     => true,
            'defaultValue' => 'example.com'
        ],
        'confirm' => [
            'prefix'       => 'y',
            'longPrefix'   => 'yes',
            'description'  => 'Say yes to every confirmation check (no prompt)',
            'noValue'      => true,
        ],
    ]);
    $climate->arguments->parse();
    $domain = $climate->arguments->get('domain');
    if (!empty($domain) && $domain !== 'example.com') {
        try {
            $confirm = $climate->arguments->get('confirm');
            $user = findUserFromExistingDomain($domain);
            $climate->bold()->underline()->out('Removal of YesWiki');
            $climate->out('This will remove <bold>'.$domain.'</bold> with the user <bold>'.$user.'</bold>'."\n");
            $input = $climate->confirm('Shall we really do it ?');
            if ($confirm || $input->confirmed()) {
                // enlever la db et le user sql
                removeMySQLUserAndDatabase($user);

                // enlever la config nginx et la conf php-fpm
                removeNginxConfig($domain);
                removePhpFpmConfig($user);

                // enlever le user unix et son home
                removeUnixUser($user);
                $climate->shout(
                    'The yeswiki on <bold>'.$domain.'</bold> was successfully removed, congrats ! 🎉'."\n"
                );
                // TODO : send log, send email
            } else {
                $climate->info('Ok, let\'s stop here...');
            }
        } catch (Exception $e) {
            $climate->error('ERROR : '.$e->getMessage());
        }
    } else {
        $climate->usage();
    }
} else {
    $climate->error('ERROR : this script needs root privilege to run.');
    exit;
}