<?php

function get_sysstat_data($metric = null, $server_id = null) {

    global $db;

    $query = 'SELECT * FROM sysstat';
    $bind_array = array();

    if (!is_null($server_id)) {
        $query .= ' WHERE server_id = :server_id';
        $bind_array[':server_id'] = intval($server_id);
    }

    if (!is_null($metric)) {
    	$query .= ' WHERE metric = :metric';
    	$bind_array[':metric'] = $metric;
    }

    if (!is_null($metric) && !is_null($server_id))
        $query .= ' LIMIT 1';

    return $db->exec_query($query, $bind_array);
}

function set_sysstat_data($metric, $value, $server_id = 0) {

	global $db;

	$query = 'REPLACE INTO sysstat (server_id, metric, value) VALUES (:server_id, :metric, :value)';
	$bind_array = array(
        ':server_id' => intval($server_id),
		':metric' => $metric,
		':value'  => $value,
		);

	return $db->exec_query($query, $bind_array);
}


// exit with message & return code is non-ok value
// if metric is set, we set that to SUBSYS_ERROR
function subsys_exit($message, $metric = null) {

    log_error(LOG_TYPE_SYSTEM, $message);

    if (!is_null($metric))
        set_sysstat_data($metric, SUBSYS_ERROR);

    exit(1);
}

function subsys_get_options($default_max_time = 60) {

    global $debug;
    global $max_time;
    global $master_poll;
    global $server;
    global $user;

    $long_options = array('debug', 'max-time:', 'master-poll', 'server:', 'user:');
    $options = getopt('', $long_options);

    $debug = false;
    if (isset($options['debug']))
        $debug = true;
    if ($debug)
        echo "\nOPERATING IN DEBUG MODE\n\n";

    $master_poll = false;
    if (isset($options['master-poll']))
        $master_poll = true;

    if (isset($options['max-time']) && is_numeric($options['max-time']) && $options['max-time'] > 0)
        $max_time = $options['max-time'];
    else
        $max_time = $default_max_time;

    if (isset($options['server']) && is_numeric($options['server']) && $options['server'] > 0)
        $server = $options['server'];

    if (isset($options['user']))
        $user = $options['user'];

}