/*
** SellaNMS
** $Id: discovery.cxx,v 2.42 2005/03/31 18:57:12 sella Exp $
** Copyright (c) 2001-2005 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

#ifdef HAVE_CONFIG_H
	#include "config.h"
#endif

#include "discovery.h"
#include "debug.h"
#include "template_func.h"
#include "netblock.h"
#include "storagedata.h"
#include <stl/queue>
#include <stl/algorithm>

Discovery::Discovery() {
	this->name.append(" discovery");

	has_scheduler = true;
	has_execute = false;
}

RESULT Discovery::handleTraceOptions() {
	/* Handle trace-options */
	if (trace.sql)
		storage.setDebug();

	if (trace.policy_sql) {
		inputPolicy.setDebug();
		outputPolicy.setDebug();
	}

	Module::handleTraceOptions();

	if (trace.policy_in && !inputPolicy.empty()) {
		if (trace.config) {
			inputPolicy.print();
		}
		inputPolicy.setTraceIn(true);
	}

	if (trace.policy_out && !outputPolicy.empty()) {
		if (trace.config) {
			outputPolicy.print();
		}
		outputPolicy.setTraceOut(true);
	}

	return SUCCESS;
}

RESULT Discovery::readKnownAddress() {
	RESULT result = FAILURE;
	long size;
	vector<string>::iterator v_it;

	variable_binding_t	policy_input;
	variable_binding_t	policy_output;

	StorageData data;

	if (storage.query(data, "SELECT ip from discovery_icmp") == SUCCESS) {
		while (data.nextRow()) {
			data.getString(policy_input["prefix"], "ip");
			policy_input["prefix-except"] = policy_input["prefix"];

			if (this->inputPolicy.evaluate(policy_output, policy_input) != ACTION_REJECT) {
				netblocks.insert(netblocks.begin(), policy_input["prefix"]);
			}
		}
		result = SUCCESS;
	} else {
		LMSG("NOTICE: Failed to read data (netblocks) in discovery.");
	}

	/* Sort and Uniq the netblocks */
	sort(netblocks.begin(), netblocks.end());
	v_it = unique(netblocks.begin(), netblocks.end());
	netblocks.erase(v_it, netblocks.end());

	return result;
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim600: fdm=marker
** vim: noet ts=3 sw=3
*/
