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

// CPU
function getCpuUsage() {
    $stat1 = file('/proc/stat');
    usleep(500000); // less load
    $stat2 = file('/proc/stat');
    $info1 = explode(" ", preg_replace("/\s+/", " ", $stat1[0]));
    $info2 = explode(" ", preg_replace("/\s+/", " ", $stat2[0]));
    $idle1 = $info1[4];
    $idle2 = $info2[4];
    $total1 = array_sum($info1);
    $total2 = array_sum($info2);
    $total = $total2 - $total1;
    $idle = $idle2 - $idle1;
    $cpu = round(100 * (($total - $idle) / $total), 2);
    return $cpu;
}

// RAM
function getRamUsage() {
    $data = file('/proc/meminfo');
    $info = [];
    foreach ($data as $line) {
        list($key, $value) = explode(":", $line);
        $info[$key] = trim(preg_replace("/[^0-9]/", "", $value));
    }
    $total = $info['MemTotal'];
    $free  = $info['MemAvailable'];
    $used = $total - $free;
    return [
        'total' => round($total / 1024),
        'used'  => round($used / 1024),
        'percent' => round(($used / $total) * 100, 2)
    ];
}

// SWAP
function getSwapUsage() {
    $data = file('/proc/meminfo');
    $info = [];
    foreach ($data as $line) {
        list($key, $value) = explode(":", $line);
        $info[$key] = trim(preg_replace("/[^0-9]/", "", $value));
    }
    $total = $info['SwapTotal'];
    $free  = $info['SwapFree'];
    if ($total == 0) return ['total'=>0,'used'=>0,'percent'=>0];
    $used = $total - $free;
    return [
        'total' => round($total / 1024),
        'used'  => round($used / 1024),
        'percent' => round(($used / $total) * 100, 2)
    ];
}

echo json_encode([
    'cpu'  => getCpuUsage(),
    'ram'  => getRamUsage(),
    'swap' => getSwapUsage(),
]);
