/*
	zillion.m
	Tue Aug 27 09:32:29 CEST 2002

	Zillion is a Server application for scheduling tasks on slave machines.
	Due to the virtues of GNUstep it is capable of servicing, both, real time
	and number crunching applications.
 */

#import <Foundation/Foundation.h>
#import	"ZillionServer.h"
#import	"NSProcessInfo+getopt.h"

int main(int argc, const char **argv)
{
	NSAutoreleasePool	*mainPool = [[NSAutoreleasePool alloc] init];

	ZillionServer		*serverObject;
	NSConnection		*theConnection;
	NSDate				*distantFuture = [NSDate distantFuture];
	NSRunLoop			*currentRunLoop = [NSRunLoop currentRunLoop];
	NSProcessInfo		*proc = [NSProcessInfo processInfo];
	NSDictionary		*options = [proc getOptionsFromSpecification:[NSArray arrayWithObjects:
		@"serverName=s", @"doRespawn", @"terminate", nil]
		defaults:[NSDictionary dictionaryWithObjectsAndKeys:
			ZILLION_SERVER_NAME, @"serverName", argYES, @"doRespawn", 
		nil]];
	NSString			*serverName = [options objectForKey:@"serverName"];
	BOOL				doRespawn = [[options objectForKey:@"doRespawn"] intValue];

	if ([options objectForKey:@"terminate"]) {
		NSLog(@"Shutting down Zillion Server");

		serverObject = [[NSConnection rootProxyForConnectionWithRegisteredName:ZILLION_SERVER_NAME
			host:@"*"] retain];
		if (!serverObject)
			NSLog(@"No zillion server is running");
		else
			[serverObject terminate];

		[mainPool release];
		return 0;
	}

	NSLog(@"Starting server [%@, respawning:%@]...", serverName, doRespawn? @"YES": @"NO");

	serverObject = [[ZillionServer alloc] initWithRespawnStatus:doRespawn];
	theConnection = [NSConnection defaultConnection];
	[theConnection setRootObject:serverObject];
	// debugging code
	//[theConnection setIndependentConversationQueueing:YES];
	if ([theConnection registerName:serverName] == NO) {
		/* Handle error. */
		NSLog(@"Could not register name with PortName server");
	}
	while (![serverObject serverToGoDown])
	{
		[currentRunLoop acceptInputForMode:NSDefaultRunLoopMode beforeDate:distantFuture];
	}

	NSLog(@"...exiting server.", 1);
	[serverObject release];

	[mainPool release];
	return 0;
}
