<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Danoral\U;
use App\Events\EventLog;

class KillProcess extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'killprocess';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Kill Process';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $u = new U;
        $u->isEcho = true;
        $u->log = '';
        $u->eLinea("inicio killprocess");

        $eventLog = new EventLog;
        $eventLog->fill([
            'dateEvent'     => date("Y-m-d H:i:s"),
            'codEvent'      => EventLog::$COD_EVENT_KILL_PROCESS,
            'idUsuario'     => 100100040000000001,
            'origenEvent'   => 1001,
            'IPEvent'       => ''
        ]);
        $eventLog->save();

        $procesos = preg_split('/[\n]+/', shell_exec('pgrep php-cgi'));

        while(count($procesos) > 10) {

            print_r($procesos);

            $pkill = shell_exec("pkill -9 -o -e php-cgi");
            $u->eLinea("nro.Procesos: ". count($procesos) ." | kill: $pkill");

            sleep(5);

            $procesos = preg_split('/[\n]+/', shell_exec('pgrep php-cgi'));

        } 

        //return $u->logList;

        return Command::SUCCESS;
    }
}
