<?php namespace App\Command; use App\Application; use App\Model\Fan; use App\Service\SystemCtl; use App\Service\Utils; use App\Subroutines\Fan\EditFan; use App\Subroutines\InitializeConfig; use GetOpt\GetOpt; use Hugga\Console; use Hugga\Input\Question\Choice; use Hugga\Input\Question\Confirmation; class Config extends AbstractCommand { protected $name = 'config'; protected $description = 'Generate or update fan configuration'; public function __construct(Application $app, Console $console) { parent::__construct($app, $console); } public function handle(GetOpt $getOpt): int { if (posix_getuid() !== 0) { $this->warn('This programm has to run as root'); return 1; } if ($this->getOption('quiet')) { $this->warn('This command requires user interaction'); return 1; } $ranBefore = SystemCtl::isActive('fan-ctrl'); if (!SystemCtl::stop('fan-ctrl')) { $this->warn('fan-ctrl could not be stopped'); return 1; } $fanConfig = $this->app->fanConfig; try { $fanConfig->readConfig(); } catch (\Throwable $e) { $this->error('Unable to read config: ' . $e->getMessage()); } if (!$fanConfig->hasFans()) { if ($this->app->get(InitializeConfig::class)->main() > 0) { return 1; } } $actions = new Choice([ 'edit a fan', 'add a sensor', 'edit a sensor', 'add a rule', 'edit a rule', 'save and exit', 'exit without saving', ], 'What next?', 'save and exit'); do { $fanConfig->display($this->console); $answer = $this->ask($actions); switch ($answer) { case 'edit a fan': if ($fan = $this->selectFan($fanConfig->getFans())) { $this->app->get(EditFan::class)->main($fan); } break; case 'exit without saving': break 2; case 'save and exit': $fanConfig->save(); break 2; default: $this->warn('not implemented'); break; } } while (true); if ($ranBefore) { SystemCtl::start('fan-ctrl'); } return 0; } protected function selectFan(array $fans): ?Fan { $choices = array_keys($fans); $choices[] = 'cancel'; $question = new Choice($choices); $question->returnKey(); $answer = $this->ask($question); return $choices[$answer] === 'cancel' ? null : $fans[$choices[$answer]]; } }