<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Command;

use Neos\Flow\Annotations as Flow;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Newland\NeosCommon\Command\AbstractCommandController;
use function Safe\pcntl_exec;

class DbCommandController extends AbstractCommandController
{

    /**
     * @var array
     * @Flow\InjectConfiguration(package="Neos.Flow", path="persistence.backendOptions")
     */
    protected $backendOptions;

    /**
     * Opens a CLI connection to the currently configured database.
     */
    public function openCommand(): void
    {
        if ($this->backendOptions['driver'] !== 'pdo_mysql') {
            throw new InvalidConfigurationException('This command can only be used with pdo_mysql driver');
        }

        $this->exec([
            'mysql',
            '--host=' . $this->backendOptions['host'],
            '--user=' . $this->backendOptions['user'],
            '--password=' . $this->backendOptions['password'],
            $this->backendOptions['dbname']
        ]);
    }

    private function exec(array $command): void
    {
        $this->outputLine('$ ' . implode(' ', $command));
        pcntl_exec('/usr/bin/env', $command);
    }
}
