#!/usr/bin/php
<?php

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

use ombutel\email;
use ombutel\settings;
use ombutel\storage_partition;
use ombutel\SystemInfo;

if (email_sent_recently()) return;

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

if ($email == '') return;

if ($limits = load_storage_limits()) {
	$content = '';
	$stdout = shell_exec('df -h --output=size,pcent,target');//get disk usage
	$stdout = explode("\n", $stdout);
	foreach ($stdout as $line) {
		if(trim($line) != '')
		{
			$m = explode(" ", preg_replace('/\s+/',' ', trim($line)));	
			list($size, $used_percent, $mount) = $m;
			if (array_key_exists($mount, $limits)) {
				if (intval($used_percent) >= $limits[$mount]) {
					$content .= _("You are using {$used_percent} of {$size} on {$mount} \n");
				}
			}
		}
	}

	if ($content != '') {
		$subject = _("Running low on disk space at " . gethostname());
		send_email($email, $subject, $content, null, $from_mail, null, null, null, null, email::origin());
		settings::set('system_misc', 'last_check_disk', time());
	}
}

// Optimized from system_miscDB.php
function load_storage_limits() {
	$partitions = [];
	foreach (SystemInfo::diskInfo() as $path => $partition) {
		$from_db = storage_partition::find_by_path($path);
		if(array_key_exists($path, $from_db)) {
			if ($from_db[$path]->notify) {
				$partitions[$path] = $from_db[$path]->percentage;
			}
		} else { // no info in database
			$partitions[$path] = 70;
		}
	}
	return $partitions;
}

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

?>
