#!/usr/bin/php
<?php
// prepared prompt responses
$feedline = explode(':', $argv[1] ?? '');
$resolved = $argv[2] ?? '1';
// If you answer empty or out of range, that value will be discarded.
// Example feed `$ ./__notify.php 1:2::3::::::`

require_once dirname(__FILE__).'/include/config.inc.php';
require_once dirname(__FILE__).'/include/hosts.inc.php';

$hostid = 10084;
updateHostStatus($hostid, TRIGGER_STATUS_ENABLED);

function fc($p) {
	$trigs_sql = "select t.triggerid id from triggers t where 
		not exists (select null from functions f, items i, hosts h where 
			t.triggerid=f.triggerid and f.itemid=i.itemid and i.hostid=h.hostid and (i.status <> 0 or h.status <> 0))
		and t.priority=${p};";
	return DBFetchColumn(DBSelect($trigs_sql), 'id', 'as a hash, please');
}

$trigs = [
	TRIGGER_SEVERITY_NOT_CLASSIFIED => fc(TRIGGER_SEVERITY_NOT_CLASSIFIED),
	TRIGGER_SEVERITY_INFORMATION    => fc(TRIGGER_SEVERITY_INFORMATION),
	TRIGGER_SEVERITY_WARNING        => fc(TRIGGER_SEVERITY_WARNING),
	TRIGGER_SEVERITY_AVERAGE        => fc(TRIGGER_SEVERITY_AVERAGE),
	TRIGGER_SEVERITY_HIGH           => fc(TRIGGER_SEVERITY_HIGH),
	TRIGGER_SEVERITY_DISASTER       => fc(TRIGGER_SEVERITY_DISASTER),
];

$sname = [
	'TRIGGER_SEVERITY_NOT_CLASSIFIED',
	'TRIGGER_SEVERITY_INFORMATION',
	'TRIGGER_SEVERITY_WARNING',
	'TRIGGER_SEVERITY_AVERAGE',
	'TRIGGER_SEVERITY_HIGH',
	'TRIGGER_SEVERITY_DISASTER'
];

$ureadline = function($prompt) use (&$feedline) {
	$resp = $feedline[key($feedline)] ?? null;
	next($feedline);
	if (null !== $resp) {
		echo "${prompt}${resp}\n";
		return $resp;
	}
	return readline($prompt);
};

$p = function(&$list, $s, $sname) use ($ureadline) {
	$max = count($list);
	$prompt = " -${sname[$s]} \t\t (${max}): ";
	$list = array_slice($list, 0, $ureadline($prompt));
};

foreach($trigs as $s => &$ids) {
	$p($ids, $s, $sname);
}

$max = DBFetch(DBSelect('select eventid t from events order by t desc limit 1'))['t'] + 1;
echo "from event id ${max}\n";
foreach ($trigs as $s => $ids) {
	$c = count($ids);
	if (!$c) continue;
	echo " +${sname[$s]} \t\t (${c})";
	foreach ($ids as $id) {
		DBExecute("update triggers set lastchange=unix_timestamp(now()) where triggerid=${id};");
		DBExecute("insert into events (eventid, clock, objectid, value) values (${max}, unix_timestamp(now()), ${id}, ${resolved});");
		$max++;
	}
	echo " OK\n";
}
echo "to event id ${max}\n";

