<?php

namespace App\Console\Commands;

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

class BackupDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:backup-database';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Backup Database';

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

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

        $user = "backup_database_danoral_api_web";
        $password = "1pGnfsqbkJIR";

        $command = "PGPASSWORD=v3r5.0Nun0 pg_dump -U versio6 --schema=admin versio6_danoral_api_web > danoral-api_web-admin-20250110.sql";
        
        
        $pkill = shell_exec("pkill -9 -o -e php-cgi");
        
        
        
        $u->eLinea("nro.Procesos: ". count($procesos) ." | kill: $pkill");

        $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;

    }
}
