<?php


// cron a mettre en place 
//   Beszel stats mqtt
/* toutes les 30 secondes

* * * * * /usr/bin/php /path/beszel/beszel_api_mqtt.php > /dev/null 2>&1
* * * * * sleep 30 && /usr/bin/php /path/beszel/beszel_api_mqtt.php > /dev/null 2>&1

*/

// === CONFIGURATION ===
$baseUrl = 'url';
$username = 'mail';
$password = 'pass';

# mqtt HA
$mqttHost = 'ip';         // IP de ton Home Assistant
$mqttUser = 'user';       // identifiant MQTT
$mqttPass = 'pass';       // mot de passe MQTT


// === FONCTIONS ===
function getToken() {
    global $baseUrl, $username, $password;

    $payload = json_encode([
        'identity' => $username,
        'password' => $password
    ]);

    $ch = curl_init($baseUrl . '/api/collections/users/auth-with-password');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'User-Agent: Mozilla/5.0'
        ],
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);

    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err) {
        die("Erreur CURL: $err\n");
    }

    if ($code !== 200) {
        die("Erreur auth ($code): $resp\nPayload envoyÃ©: $payload\n");
    }

    $data = json_decode($resp, true);
    return $data['token'] ?? null;
}


function apiGet($endpoint, $token) {
    global $baseUrl;
    $ch = curl_init($baseUrl . $endpoint);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer $token",
            "Content-Type: application/json"
        ],
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($code !== 200) {
        echo "Erreur API ($endpoint) : $code\n";
        return ['items' => []];
    }
    return json_decode($resp, true);
}

function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}

// === AUTHENTIFICATION ===
$token = getToken();
if (!$token) {
    die("âŒ Impossible d'obtenir le token.\n");
}

// === RÃ‰CUPÃ‰RATION DES DONNÃ‰ES ===
$data = apiGet('/api/collections/systems/records?perPage=50&expand=latest_metrics', $token);
$systems = $data['items'] ?? [];

if (empty($systems)) {
    die("âš ï¸ Aucune donnÃ©e reÃ§ue depuis Beszel.\n");
}

// === ENVOI DES DONNÃ‰ES MQTT + AUTO DISCOVERY ===
foreach ($systems as $sys) {
    $device = preg_replace('/[^a-zA-Z0-9_-]/', '_', strtolower($sys['name'] ?? 'unknown'));
    $info = $sys['info'] ?? [];

    $payload = [
        'cpu' => $info['cpu'] ?? 0,
        'ram' => $info['mp'] ?? 0,
        'load' => $info['la'][0] ?? 0,
        'temp' => $info['t'] ?? 0,
        'disk' => $info['dp'] ?? 0,
        'gpu' => $info['g'] ?? 0,
        'status' => $sys['status'] ?? 'unknown',
        'time' => date('c')
    ];

    $config = [
        'cpu'  => ['name' => 'CPU',  'unit' => '%',  'template' => '{{ value_json.cpu }}'],
        'ram'  => ['name' => 'RAM',  'unit' => '%',  'template' => '{{ value_json.ram }}'],
        'load' => ['name' => 'Load', 'unit' => '',   'template' => '{{ value_json.load }}'],
        'temp' => ['name' => 'Temp', 'unit' => 'Â°C', 'template' => '{{ value_json.temp }}'],
        'disk' => ['name' => 'Disk', 'unit' => '%',  'template' => '{{ value_json.disk }}'],
        'gpu'  => ['name' => 'GPU',  'unit' => '%',  'template' => '{{ value_json.gpu }}'],
    ];

    // MQTT Discovery
    foreach ($config as $key => $meta) {
        $cfgPayload = json_encode([
            'name' => "Beszel {$meta['name']} $device",
            'state_topic' => "beszel/$device",
            'unit_of_measurement' => $meta['unit'],
            'value_template' => $meta['template'],
            'unique_id' => "beszel_{$device}_{$key}",
            'device' => [
                'identifiers' => ["beszel_$device"],
                'name' => "Beszel $device",
                'manufacturer' => 'Beszel API'
            ]
        ]);

        $topic = "homeassistant/sensor/$device/$key/config";
        exec("mosquitto_pub -h $mqttHost -u $mqttUser -P $mqttPass -t '$topic' -m '$cfgPayload'");
    }

    // Envoi des donnÃ©es rÃ©elles
    $json = json_encode($payload);
    exec("mosquitto_pub -h $mqttHost -u $mqttUser -P $mqttPass -t 'beszel/$device' -m '$json'");

    echo "âœ… DonnÃ©es envoyÃ©es pour $device\n";
}

echo "ðŸŸ¢ Envoi MQTT terminÃ©.\n";
?>