<?php
/**
 * notifar.io — скрипт мониторинга ресурсов сервера (CPU, RAM, диск, load average).
 * Положите файл на сервер и укажите его адрес в мониторе «Ресурсы сервера».
 * Секрет: define('NOTIFAR_SECRET', '...') до подключения файла или переменная окружения NOTIFAR_SECRET.
 */
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');

$secret = defined('NOTIFAR_SECRET') ? NOTIFAR_SECRET : (getenv('NOTIFAR_SECRET') ?: '');
if ($secret !== '') {
    $got = $_SERVER['HTTP_X_NOTIFAR_SECRET'] ?? ($_GET['secret'] ?? '');
    if (!hash_equals($secret, (string)$got)) { http_response_code(403); echo json_encode(['error' => 'forbidden']); exit; }
}

function nf_cpu() {
    if (!is_readable('/proc/stat')) return null;
    $read = function () { $l = explode(' ', preg_replace('/\s+/', ' ', trim(explode("\n", file_get_contents('/proc/stat'))[0]))); array_shift($l); $l = array_map('intval', $l); $idle = $l[3] + ($l[4] ?? 0); return [array_sum($l), $idle]; };
    [$t1, $i1] = $read(); usleep(200000); [$t2, $i2] = $read();
    $dt = $t2 - $t1; if ($dt <= 0) return null;
    return round((1 - ($i2 - $i1) / $dt) * 100, 1);
}
function nf_ram() {
    if (!is_readable('/proc/meminfo')) return null;
    $m = []; foreach (file('/proc/meminfo') as $line) { if (preg_match('/^(\w+):\s+(\d+)/', $line, $x)) $m[$x[1]] = (int)$x[2]; }
    if (empty($m['MemTotal'])) return null;
    $avail = $m['MemAvailable'] ?? ($m['MemFree'] + ($m['Buffers'] ?? 0) + ($m['Cached'] ?? 0));
    return round((1 - $avail / $m['MemTotal']) * 100, 1);
}
function nf_disks() {
    $out = [];
    $mounts = ['/'];
    if (is_readable('/proc/mounts')) foreach (file('/proc/mounts') as $l) { $p = explode(' ', $l); if (isset($p[1]) && preg_match('#^/(data|home|var|srv|mnt/\w+)$#', $p[1]) && preg_match('/^(ext|xfs|btrfs|zfs)/', $p[2] ?? '')) $mounts[] = $p[1]; }
    foreach (array_unique($mounts) as $mnt) { $t = @disk_total_space($mnt); $f = @disk_free_space($mnt); if ($t) $out[] = ['mount' => $mnt, 'pct' => round((1 - $f / $t) * 100, 1)]; }
    return $out;
}
$disks = nf_disks();
$load = function_exists('sys_getloadavg') ? array_map(fn($v) => round($v, 2), sys_getloadavg()) : null;
$uptime = is_readable('/proc/uptime') ? (int)floatval(file_get_contents('/proc/uptime')) : null;
echo json_encode([
    'cpu' => nf_cpu(),
    'ram' => nf_ram(),
    'disk' => $disks[0]['pct'] ?? null,
    'disks' => $disks,
    'load' => $load,
    'uptime' => $uptime,
    'custom' => new stdClass(),
    'generated_at' => date('c'),
], JSON_UNESCAPED_UNICODE);
