<?php

namespace App\Commands;

use Illuminate\Console\Scheduling\Schedule;
use LaravelZero\Framework\Commands\Command;

use App\Facades\Install;

/**
 *  Install php-fpm
 *
 *  @author Björn Hase, Tentakelfabrik
 *  @license http://opensource.org/licenses/MIT The MIT License
 *  @link https://gitea.tentakelfabrik.de/Tentakelfabrik/mcp
 *
 */
class PhpFpmInstallCommand extends Command
{
    const FILE_PREFIX = '/etc/php';
    const FILE_SUFFIX = '/fpm/pool.d/www.conf';

    // packages to install
    const PACKAGES = 'php-mysql php-pear php-gd php-common php-curl php-json php-mbstring php-xml php-zip php-bcmath';

    /**
     * The signature of the command.
     *
     * @var string
     */
    protected $signature = 'php-fpm:install {--user=}';

    /**
     * The description of the command.
     *
     * @var string
     */
    protected $description = 'Install php-fpm';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('Php-fpm installing...');

        exec('apt update 2>&1', $output);
        exec('apt install -y php-fpm '.self::PACKAGES.' 2>&1', $output);

        // @TODO apt add a Warning for no good, in a later version output will be scanned for helpfull infos
        $this->line(implode("\n", Install::filterAptMessages($output)));

        // scan for all versions
        foreach(scandir(self::FILE_PREFIX) as $directory) {

            // get path to www.conf
            $file = self::FILE_PREFIX.'/'.$directory.self::FILE_SUFFIX;

            if (file_exists($file)) {

                // get user
                $user = $this->option('user');

                if ($user) {
                    $output = [];

                    $this->info('Php-fpm change user...');
                    exec('sed -i "s/user = www-data/user = '.$user.'/g" '.$file, $output);
                    exec('sed -i "s/group = www-data/group = '.$user.'/g" '.$file, $output);

                    exec('sed -i "s/listen.owner = www-data/listen.owner = '.$user.'/g" '.$file, $output);
                    exec('sed -i "s/listen.group = www-data/listen.group = '.$user.'/g" '.$file, $output);

                    $this->line(implode("\n", $output));
                }

                $output = [];

                $this->info('Php-fpm change mode...');
                exec('sed -i "s/;listen.mode = 0660/listen.mode = 0660/g" '.$file, $output);

                $this->line(implode("\n", $output));
            }
        }

        // check if nginx is ready and installed
        if (Install::isReady('php-fpm')) {
            $this->info('Php-fpm installing...Success! \o/');
        } else {
            $this->error('Failed! Please check log-file!');
        }
    }
}