<?php
ignore_user_abort(true);
set_time_limit(0);

header('Content-Type: application/json');

$script   = __DIR__ . '/gps_server_mysql.php';
$pidFile  = __DIR__ . '/gps_server.pid';
$logFile  = __DIR__ . '/gps_server.log';
$lockFile = __DIR__ . '/gps.lock';

$action = $_POST['action'] ?? "";

// ----------------------
function isRunning($pid){
    return file_exists("/proc/$pid");
}
// ----------------------

switch($action){

    case 'start':

        touch($lockFile); // Watchdog debe mantenerlo encendido

        if(file_exists($pidFile)){
            $pid = trim(file_get_contents($pidFile));
            if(isRunning($pid)){
                echo json_encode(["status"=>"error","msg"=>"El servidor ya estaba corriendo"]);
                exit;
            }
        }

        $cmd = "nohup php $script > $logFile 2>&1 & echo $!";
        $pid = trim(shell_exec($cmd));

        file_put_contents($pidFile, $pid);

        echo json_encode(["status"=>"success", "pid"=>$pid, "msg"=>"Servidor iniciado"]);
        break;



    case 'stop':

        if(file_exists($lockFile)) unlink($lockFile);

        if(!file_exists($pidFile)){
            echo json_encode(["status"=>"error","msg"=>"No hay PID"]);
            exit;
        }

        $pid = trim(file_get_contents($pidFile));

        if(isRunning($pid)){
            exec("kill -9 $pid");
        }

        @unlink($pidFile);

        echo json_encode(["status"=>"success","msg"=>"Servidor detenido"]);
        break;



    case 'status':

        $running = false;
        $uptime = 0;

        if(file_exists($pidFile)){
            $pid = trim(file_get_contents($pidFile));
            if(isRunning($pid)){
                $running = true;
                $uptime = time() - filemtime($pidFile);
            }
        }

        $logs = file_exists($logFile)
            ? shell_exec("tail -n 50 $logFile")
            : "";

        echo json_encode([
            "running" => $running,
            "uptime"  => $uptime,
            "logs"    => $logs,
            "lock"    => file_exists($lockFile)
        ]);
        break;

    default:
        echo json_encode(["status"=>"error","msg"=>"Acción no válida"]);
}
?>
