<?php

namespace Shm\ShmLoop;

use Shm\ShmCmd\Cmd;
use Shm\ShmUtils\ShmInit;

class ShmLoop
{

    public static function loopHandler()
    {

        Cmd::command("shmLoop", function () {

            self::loop();
        });
    }

    public static function loop()
    {
        if (!function_exists('exec')) {
            $error = new \RuntimeException("Function exec() is disabled");
            ShmInit::sendOnError($error);

            return;
        }

        foreach (Cmd::getLoopCommands() as $cmd) {
            $command = "php ./index.php " . escapeshellarg($cmd);

            $output = [];
            echo "RUN CMD: " . $command . PHP_EOL;
            echo "--------------------------------" . PHP_EOL;
            exec($command, $output, $return_var);

            if ($output) {
                echo implode(PHP_EOL, $output) . PHP_EOL;
            } else {
                echo "NO OUTPUT" . PHP_EOL;
            }
            echo "--------------------------------" . PHP_EOL;

            if ($return_var !== 0) {
                $message = "Command '{$cmd}' failed with exit code {$return_var}";
                $error = new \RuntimeException($message);
                ShmInit::sendOnError($error);
            }
        }
    }
}
