#!/usr/bin/php
<?php
/*
# description: Start Flow-Capture
# chkconfig: 2345 95 00
*/

$cacti_base = '/var/www/html/cacti';

include_once($cacti_base . '/include/cli_check.php');
include_once($cacti_base . '/lib/poller.php');

$shortopts = 'VvHh';
$longopts = array(
	'systemd',
	'version',
	'help',
);

$options = getopt($shortopts, $longopts);

if (isset($options['systemd'])) {
	start();
} else {
	if (isset($_SERVER['argv'][1])) {
		switch (strtolower($_SERVER['argv'][1])) {
		case 'start':
			start();
			break;
		case 'stop':
			stop();
			break;
		case 'restart':
			restart();
			break;
		default:
			print 'Usage: /etc/init.d/flow-capture {start|stop|restart}' . PHP_EOL;
			break;
		}
	}
}

function start() {
	global $cacti_base, $systemd;

	print 'NOTE: Starting Flow Collection' . PHP_EOL;

	$devices = db_fetch_assoc('SELECT * FROM plugin_flowview_devices');
	$legacy  = db_fetch_cell('SELECT COUNT(*) FROM plugin_flowview_devices WHERE cmethod = 1');

	if (!empty($devices)) {
		foreach ($devices as $device) {
			$php_binary = read_config_option('path_php_binary');
			print "NOTE: Launching cacti-flow-capture as '" . $cacti_base . '/plugins/flowview/flow_collector.php --listener-id=' . $device['id'] . "'" . PHP_EOL;

			if ($systemd) {
				shell_exec($php_binary . ' -q ' . $cacti_base . '/plugins/flowview/flow_collector.php --listener-id=' . $device['id']);
			} else {
				exec_background($php_binary, ' -q ' . $cacti_base . '/plugins/flowview/flow_collector.php --listener-id=' . $device['id']);
			}
		}
	} else {
		print 'NOTE: No Flow Capture Listeners configured' . PHP_EOL;
	}			
}

function stop() {
	global $cacti_base;

	print 'NOTE: Stopping Flow Collection' . PHP_EOL;

	$devices    = db_fetch_assoc('SELECT * FROM plugin_flowview_devices');
	$php_binary = read_config_option('path_php_binary');

	if (cacti_sizeof($devices)) {
		shell_exec('ps ax | grep -v \'grep\' | grep \'flow_collector.php\' | awk \'{ print $1 }\' | xargs kill');
	}			
}

function restart() {
	stop();
	start();
}
