<?php
declare(strict_types=1);

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

$errors = [];

$status = json_decode(
    file_get_contents('/var/www/html/service-status.json'),
    true
);

if (!$status) {
    http_response_code(500);
    die(json_encode([
        'error' => 'Unable to read status file'
    ]));
}

// MySQL
try {
    $db = new mysqli(
        '127.0.0.1',
        'truehostuptime',
        'truehostuptime1',
        'mysql'
    );

    $db->query("SELECT 1");
    $db->close();

} catch (Throwable $e) {
    $errors[] = 'MySQL';
}

// Ports
function checkPort($port)
{
    $fp = @fsockopen('127.0.0.1', $port, $e, $s, 2);

    if ($fp) {
        fclose($fp);
        return true;
    }

    return false;
}

if (!checkPort(2087) && !checkPort(2083))
    $errors[]='cPanel';

if (!checkPort(25))
    $errors[]='Exim';

foreach ([
    'jetbackup'=>'JetBackup',
    'lfd'=>'LFD',
    'csf'=>'CSF',
    'litespeed'=>'LiteSpeed'
] as $k=>$v)
{
    if (empty($status[$k])) {
        $errors[]=$v;
    }
}

if ($errors) {

    http_response_code(500);

    echo json_encode([
        'status'=>'error',
        'services'=>$errors,
        'updated'=>$status['updated']
    ], JSON_PRETTY_PRINT);

    exit;
}

echo json_encode([
    'message'=>'All services are online'
], JSON_PRETTY_PRINT);