<?php
declare(strict_types=1);

// Database connection settings
$dbHost = 'localhost';
$dbUser = 'truehostuptime';
$dbPassword = 'truehostuptime1';
$dbName = 'mysql';

$errors = [];

// 1. MySQL Check
$conn = @new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
if ($conn->connect_error) {
    $errors[] = 'MySQL is down: Connection failed - ' . $conn->connect_error;
} else {
    $result = @$conn->query('SELECT 1');
    if (!$result) {
        $errors[] = 'MySQL is down: Query failed - ' . $conn->error;
    }
    $conn->close();
}

// Helper function to check systemd service status using proc_open
function checkSystemdService($serviceName) {
    $descriptorspec = [
        0 => ["pipe", "r"],  // stdin
        1 => ["pipe", "w"],  // stdout
        2 => ["pipe", "w"]   // stderr
    ];
    
    $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 - Check port 5432
if (!checkServiceBySocket(5432)) {
    $errors[] = 'PostgreSQL is down';
}

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

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

// 5. CSF Check - Use systemd (csf.service or check lfd as CSF's daemon)
if (!checkSystemdService('csf')) {
    $errors[] = 'CSF is down';
}

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

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

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

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