#!/usr/bin/php
<?php

require_once('/usr/share/ombutel/www/includes/cli.php');
require_once('send_email.php');

use ombutel\email;
use ombutel\settings;

define('CPU_THRESHOLD', 80);
define('COOLDOWN_SECONDS', 3600);

if (email_sent_recently()) return;

$email = settings::get('system_misc', 'storageemail');
$from_mail = settings::get('system_misc', 'fromemail');

if ($email == '') return;

$cpu_usage = get_cpu_usage();

if ($cpu_usage >= CPU_THRESHOLD) {
	$top_processes = get_top_processes();
	$subject = _("High CPU usage ({$cpu_usage}%) at " . gethostname());
	$content  = "CPU usage has exceeded the threshold of " . CPU_THRESHOLD . "%.\n";
	$content .= "Current CPU usage: {$cpu_usage}%\n\n";
	$content .= "Top processes by CPU usage:\n";
	$content .= $top_processes;
	send_email($email, $subject, $content, null, $from_mail, null, null, null, null, email::origin());
	settings::set('system_misc', 'last_check_cpu', time());
}

function get_cpu_usage() {
	$output = shell_exec("top -bn1 | grep 'Cpu(s)'");
	if (preg_match('/(\d+\.?\d*)\s*id/', $output, $matches)) {
		return round(100 - floatval($matches[1]));
	}
	return 0;
}

function get_top_processes() {
	return shell_exec("ps aux --sort=-%cpu | head -11");
}

function email_sent_recently() {
	return @intval(settings::get('system_misc', 'last_check_cpu')) + COOLDOWN_SECONDS >= time();
}

?>
