<?php
/**
 * Host CPU and memory totals — used for "uncapped" user ceilings in
 * site-creation forms and elsewhere that needs to know what the box has.
 *
 * Pure /proc readers (no shell), safe defaults if reads fail.
 */

function whp_host_cpu_cores(): int {
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }

    $cores = 0;
    $cpuinfo = @file_get_contents('/proc/cpuinfo');
    if ($cpuinfo !== false) {
        // One "processor : N" line per logical CPU
        $cores = preg_match_all('/^processor\s*:/m', $cpuinfo);
    }

    if ($cores < 1) {
        // Fallback: /sys/devices/system/cpu/online — "0-7" or "0-3,8-11"
        $online = @file_get_contents('/sys/devices/system/cpu/online');
        if ($online !== false) {
            $cores = 0;
            foreach (explode(',', trim($online)) as $part) {
                if (strpos($part, '-') !== false) {
                    [$lo, $hi] = explode('-', $part, 2);
                    $cores += ((int)$hi - (int)$lo + 1);
                } elseif ($part !== '') {
                    $cores += 1;
                }
            }
        }
    }

    $cached = $cores > 0 ? $cores : 8;  // 8-core safe default
    return $cached;
}

function whp_host_memory_mb(): int {
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }

    $meminfo = @file_get_contents('/proc/meminfo');
    if ($meminfo !== false && preg_match('/^MemTotal:\s+(\d+)\s+kB/m', $meminfo, $m)) {
        $mb = (int)floor((int)$m[1] / 1024);
        $cached = $mb > 0 ? $mb : 8192;
        return $cached;
    }

    $cached = 8192;  // 8 GB safe default
    return $cached;
}
