<?php
header('Content-Type: application/json');
header('Cache-Control: no-store');

$content = @file_get_contents('/proc/mdstat');
if (!$content) { echo json_encode(['error' => 'unreadable']); exit; }

$arrays  = [];
$current = null;

foreach (explode("\n", $content) as $line) {
    if (preg_match('/^(md\d+)\s*:\s*(\w+)\s+(\w+)\s+(.+)$/', $line, $m)) {
        $current = $m[1];
        $arrays[$current] = ['name' => $m[1], 'level' => $m[3], 'health' => 'ok', 'bitmap' => '', 'detail' => ''];
    }
    if ($current && preg_match('/\[(\d+)\/(\d+)\]\s*\[([U_]+)\]/', $line, $m)) {
        $arrays[$current]['bitmap'] = $m[3];
        $arrays[$current]['active'] = (int)$m[2];
        $arrays[$current]['total']  = (int)$m[1];
        if ((int)$m[2] < (int)$m[1] || str_contains($m[3], '_'))
            $arrays[$current]['health'] = 'degraded';
    }
    if ($current && preg_match('/(resync|recovery)\s*=\s*([\d.]+%)/i', $line, $m)) {
        $arrays[$current]['health']  = 'recovering';
        $arrays[$current]['detail']  = "{$m[1]} {$m[2]}";
    }
}

$list    = array_values($arrays);
$healthy = !array_filter($list, fn($a) => $a['health'] !== 'ok');

echo json_encode(['healthy' => $healthy, 'arrays' => $list]);
