/* Copyright (c) 1992 by NightShade Software.  All rights reserved.
 *    You may modify and (hopefully) improve this code if you keep the
 *    original copyright messages, don't sell it, and share your improvements
 *    with with the World.
 *
 * NAME
 *     main() -- Broadcast.daemon
 *
 * DESCRIPTION
 *     A Workspace daemon used to broadcast a message to the user logged
 *     in to the console from a user logged in remotely.
 *
 * COMMENTS/PROBLEMS
 *     You get what you pay for...
 *
 * AUTHOR/DATE CREATED
 *     Gary Ritchie/December 22, 1992
 *
 * REVISIONS
 *
 */

#import <appkit/Application.h>
#import <ListenerAdditions.h>
#import <BroadcastListener.h>
#import <shared.h>
#import "Controller.h"

int main(int argc, char *argv[])
{
    id theController;
    id theListener;
    NXDefaultsVector workspaceDefs = {{"LaunchPaths", ""}};
    char *orig;
    char *new;
    const char *p;
    char *str, *anotherstr;
    port_t thePort;
   
    /* See if we are already running */
    if (thePort = NXPortNameLookup(BROADCASTPORT, NULL)) {
        port_deallocate(task_self(), thePort);
	NXLogError("Broadcast.daemon already running\n");
	exit(1);
    }
    
    /* The Controller handles the Broadcast messages */
    theController = [[Controller alloc] init];
    
    /* We need an Application object for operation of Alert Panels */
    [Application new];
    [NXApp setDelegate:theController]; 
    
    /* Install ourself in the Workspace's defaults so that we are
     * launched every time the user logs in.
     */
    NXRegisterDefaults("Workspace", workspaceDefs);
    p = NXGetDefaultValue("Workspace", "LaunchPaths");
    if (!p) p = "";
    orig = NXCopyStringBuffer(p);
    new = malloc(strlen(orig) + MAXPATHLEN + 1);
    new[0] = '\0';
    str = strtok(orig, ";");
    while (str) {
        anotherstr = strstr(str, "Broadcast.daemon");
	if (!anotherstr) {
	    if (strlen(new)) strcat(new, ";");
            strcat(new, str);
	}
	str = strtok(NULL, ";");
    }
    if (strlen(new)) strcat(new, ";");
    strcat(new, argv[0]);
    NXWriteDefault("Workspace", "LaunchPaths", new);
    free(orig);
    free(new);
    
    /* Allocate a listener and publicly advertise it */
    theListener = [[BroadcastListener alloc] init];
    [theListener setDelegate:theController];
    if ([theListener publicCheckInAs:BROADCASTPORT]) {
        [theListener free];
	[theController free];
	NXLogError("Broadcast.daemon failed to register public port.\n");
        exit(1);
    }
    [theListener addPort];
    
    [NXApp run];
    [NXApp free];
    
    return(0);
}
