#!/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-installer, install YesWiki like a professionnal 🌈🦄');

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 used for installation',
            'required'     => true,
            'defaultValue' => 'example.com'
        ],
        'type' => [
            'prefix'       => 't',
            'longPrefix'   => 'type',
            'description'  => 'Type of installation, can be "solo" or "ferme"',
            'required'     => true,
            'defaultValue' => 'solo'
        ],
        'quota' => [
            'prefix'       => 'q',
            'longPrefix'   => 'quota',
            'description'  => 'User quota for hard drive space, in bytes',
            'required'     => true,
            'defaultValue' => $_SERVER['soloquota'],
            'castTo'       => 'int'
        ],
        'herseuser' => [
            'prefix'       => 'hu',
            'longPrefix'   => 'herseuser',
            'description'  => 'Username for HTTP auth barrier',
        ],
        'hersepass' => [
            'prefix'       => 'hp',
            'longPrefix'   => 'hersepass',
            'description'  => 'Password for HTTP auth barrier',
        ],
        'confirm' => [
            'prefix'       => 'y',
            'longPrefix'   => 'yes',
            'description'  => 'Say yes to every confirmation check (no prompt)',
            'noValue'      => true,
        ],
        'nossl' => [
            'prefix'       => 'nossl',
            'longPrefix'   => 'no-ssl-certificate',
            'description'  => 'No SSL certificate and no DNS check',
            'noValue'      => true,
        ],
        'noip6' => [
            'prefix'       => 'noip6',
            'longPrefix'   => 'no-ip-v6',
            'description'  => 'No ip v6 DNS check',
            'noValue'      => true,
        ],
    ]);
    $climate->arguments->parse();
    $domain = $climate->arguments->get('domain');
    if (!empty($domain) && $domain !== 'example.com') {
        try {
            $quota = $climate->arguments->get('quota');
            $type = $climate->arguments->get('type');
            $confirm = $climate->arguments->get('confirm');
            $nossl = $climate->arguments->get('nossl');
            $noip6 = $climate->arguments->get('noip6');
            $herseUser = $climate->arguments->get('herseuser');
            $hersePass = $climate->arguments->get('hersepass');

            //$isFullDomain = !preg_match('/.'.$_SERVER['maindomain'].'$/isU', $domain, $matches, PREG_OFFSET_CAPTURE, 0);
            $isFullDomain = !preg_match('/^([a-zA-Z0-9]([-a-zA-Z0-9]{0,61}[a-zA-Z0-9])\.)([a-zA-Z0-9]{1,2}([-a-zA-Z0-9]{0,252}[a-zA-Z0-9])?)\.([a-zA-Z]{2,63})$/isU', $domain, $matches, PREG_OFFSET_CAPTURE, 0);
            if (!$nossl) {
                checkIP($domain, $isFullDomain, $noip6);
            }
            checkIfInstalled($domain);
            $needHerse = checkHerse($herseUser, $hersePass);
            $user = generateUserFromDomain($domain);
            $climate->bold()->underline()->out('Installation of YesWiki');
            $climate->out('This will install a yeswiki on <bold>'.$domain."</bold>\n".'model <bold>'.$type.'</bold>, <bold>'.preg_replace('/000000$/', 'Gb', $quota).' quota</bold>, with the user <bold>'.$user.'</bold>.'."\n".($needHerse ? 'An herse with user <bold>'.$herseUser.'</bold> and password <bold>'.$hersePass.'</bold> will be set up.' : ''));
            $input = $climate->confirm('Is it all good ?');
            if ($confirm || $input->confirmed()) {
                $unixUser = createUnixUserWithQuota($user, $quota);
                $dbUser = createSQLUserAndDatabase($user, $type);
                createNginxConfig($domain, $user, $herseUser, $hersePass, $nossl);
                createPhpFpmConfig($user);
                if ($needHerse) {
                    copyYesWikiFiles($domain, $user, $dbUser, $herseUser, $hersePass, $nossl);
                } else {
                    copyYesWikiFiles($domain, $user, $dbUser, null, null, $nossl);
                }
                $climate->shout(
                    'The yeswiki was successfully installed on <bold>http'.($nossl ? '' : 's').'://'.$domain.'</bold>, congrats ! 🎉'."\n"
                    .' Unix user : <bold>'.$unixUser['user'].'</bold> with password : <bold>'.$unixUser['password'].'</bold> was created.'."\n"
                    .'MySQL user : <bold>'.$dbUser['user'].'</bold> with password : <bold>'.$dbUser['password'].'</bold> was created for database <bold>'.$dbUser['database'].'</bold>.'."\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;
}