#!/usr/local/bin/ispcphp
<?php

// Checks for ISPConfig cronjobs that are neither running
// nor have a scheduled next run.

require_once '/usr/local/ispconfig/server/lib/config.inc.php';
require_once '/usr/local/ispconfig/server/lib/app.inc.php';

// Get backup cronjob that is not running and next run is scheduled
// at least 40 hours in the past.
$records = $app->db->queryAllRecords("SELECT name, last_run FROM sys_cron WHERE running=0 AND next_run < NOW() - INTERVAL 40 HOUR AND name='cronjob_backup' ORDER BY last_run DESC");

foreach($records as $cron) {
        $short_name = str_replace('cronjob_', '', $cron['name']);
        $glob_result = glob('/usr/local/ispconfig/server/lib/classes/cron.d/*-'.$short_name.'.inc.php');
        $file_exists = is_array($glob_result) && !empty($glob_result);

        if($file_exists) {
                echo "CRITICAL - cronjob $short_name not running since $cron[last_run] and next run not yet scheduled";
                exit(2);
        }
}

// Get all cronjobs that are not running and next run is scheduled
// at least one hour in the past.
$records = $app->db->queryAllRecords('SELECT name, last_run FROM sys_cron WHERE running=0 AND next_run < NOW() - INTERVAL 1 HOUR ORDER BY last_run DESC');

foreach($records as $cron) {
        $short_name = str_replace('cronjob_', '', $cron['name']);
        $glob_result = glob('/usr/local/ispconfig/server/lib/classes/cron.d/*-'.$short_name.'.inc.php');
        $file_exists = is_array($glob_result) && !empty($glob_result);

        if($file_exists) {
                echo "WARNING - cronjob $short_name not running since $cron[last_run] and next run not yet scheduled";
                exit(1);
        }
}

echo "OK";
exit(0);

?>
