//
// CRAM: CREATE Real-time Applications Manager
// See the copyright and acknowledgment of authors in the file COPYRIGHT
//
//// Node_main.cpp: the main() function for the CRAM node manager program ////
//
//	Usage: NodeManager node_name [listener_port emergency_port] [-restart]
//
// This is pretty simple; create a node object and let it do all the work.
//

#include "Node.h"

using namespace cram;

//// MAIN ////

int main (int argc, char *argv[]) {
	unsigned short lport, eport;
	
	if (argc < 2) {					// too few options
		printf("Usage: NodeManager node_name [listener_port emergency_port] [-restart]\n");
		exit(0);
	}
									// quick check for options
	for (int i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			if ( ! strcmp(argv[i], "-restart")) {
									// Emergency restart mode: try to read the PID file and reconnect
	} } }
		
	if (argc < 3)							// if you gave only the listener port
		lport = CRAM_NODE_PORT;
	else
		lport = atoi(argv[2]);
	if (argc < 4)							// if you gave the emergency port
		eport = CRAM_EMERGENCY_PORT;
	else
		eport = atoi(argv[3]);
	if ((lport <= 0) || (lport <= 0)) {		// check port numbers
		printf("\t[Node manage: bad ports: %d/%d]\n", lport, eport);
		exit(1);
	}
	printf("\n\t[Node manager starting]\n");
													// Create the node...
	Node * node = new Node(argv[1], lport, eport);	// the constructor does the work
	
	if (node->start_threads() != 0) {				// start the Node's listener and emergency threads
	
		printf("\t[FATAL: Node start-up failed]\n");
	} else {
		node->mAppStatus = CRAM_ON;
#ifdef SPAWN_EMERGENCY_THREAD
		pthread_join(node->mEThread, NULL);			// suspend until node emergency thread terminates
#else
		pthread_join(node->mLThread, NULL);			// or suspend until node listener thread terminates
#endif
		printf("\t[Node manager terminated]\n");
	}
													// if the node's threads exit...
	delete node;									// delete the node object
	exit(0);
}

