<?php
declare(strict_types=1);

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

// Database connection settings
$dbHost = '127.0.0.1';
$dbUser = 'truehostuptime';
$dbPassword = 'truehostuptime1';
$dbName = 'mysql';
$errors = [];

// 1. MySQL Check
try {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $conn = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
    $result = $conn->query('SELECT 1');
    if (!$result) {
        $errors[] = 'MySQL is down: Query failed - ' . $conn->error;
    }
    $conn->close();
} catch (mysqli_sql_exception $e) {
    $errors[] = 'MySQL is down: ' . $e->getMessage();
} catch (Throwable $e) {
    $errors[] = 'MySQL is down: ' . $e->getMessage();
}

// Helper function to check systemd service status using proc_open
function checkSystemdService($serviceName) {
    $descriptorspec = [
        0 => ["pipe", "r"],
        1 => ["pipe", "w"],
        2 => ["pipe", "w"]
    ];

    $process = @proc_open(
        "systemctl is-active " . escapeshellarg($serviceName),
        $descriptorspec,
        $pipes
    );

    if (!is_resource($process)) {
        return false;
    }

    $output = stream_get_contents($pipes[1]);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    proc_close($process);

    return trim($output) === 'active';
}

// Helper function to check if a port is listening
function checkServiceBySocket($port, $host = '127.0.0.1', $timeout = 2) {
    $connection = @fsockopen($host, $port, $errno, $errstr, $timeout);
    if ($connection) {
        fclose($connection);
        return true;
    }
    return false;
}

// 2. PostgreSQL Check
if (!checkServiceBySocket(5432)) {
    $errors[] = 'PostgreSQL is down';
}

// 3. cPanel Service Check
if (!checkServiceBySocket(2087) && !checkServiceBySocket(2083)) {
    $errors[] = 'cPanel is down';
}

// 4. JetBackup5 Check
if (!checkSystemdService('jetbackup5d')) {
    $errors[] = 'JetBackup5d is down';
}

// 5. CSF Check
if (!checkSystemdService('csf')) {
    $errors[] = 'CSF is down';
}

// 6. LFD Check
if (!checkSystemdService('lfd')) {
    $errors[] = 'LFD is down';
}

// 7. Exim Check
if (!checkServiceBySocket(25)) {
    $errors[] = 'Exim is down';
}

// Return response
if (!empty($errors)) {
    http_response_code(500);
    echo json_encode(['error' => implode('; ', $errors)]);
    exit;
}

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