/*
 *     Generated by the NeXT Interface Builder.
 */

#import <stdlib.h>
#import <appkit/Application.h>
#import <appkit/Panel.h>
#import <defaults.h>
#import "Main.h"
#import <sys/param.h>
#import <string.h>
#import <libc.h>

#define APPNAME "Launch"

char loginScript[MAXPATHLEN];
char logoutScript[MAXPATHLEN];

// Load the interface if it isn't already loaded.
void loadnib(void)
{
	static loaded=0;
	if (loaded==0)
	{
		NXApp = [Application new];
		[NXApp loadNibSection:"Launch.nib" owner:NXApp];		
	}
}

// Execute the script by overlaying our own image.
void doLaunch(void)
{
	execl(loginScript, ".Launch", 0);
	// If we ever get to here, then something went wrong with the execution.
	loadnib();
	NXRunAlertPanel(APPNAME, "Cannot execute script %s",
		"OK", NULL, NULL, loginScript);
}

void main(int argc, char *argv[])
{
	char const *def;
	
	static NXDefaultsVector Defaults = {
		{"NXAutoLaunch", "NO"},
		{"OnAutoLaunch", "Execute"},
		{"OnLogout", "Execute"},
		{NULL}
		};

	// Register our defaults.
	NXRegisterDefaults(APPNAME, Defaults);

	// Form the pathname of the scripts to be executed.
	sprintf(loginScript, "%s/.Launch", getenv("HOME"));
	sprintf(logoutScript, "%s/.Logout", getenv("HOME"));

	// Check the defaults to see if the app was auto-launched.
	def = NXGetDefaultValue(APPNAME, "NXAutoLaunch");
	
	if (strcmp(def, "YES")==0)
	{
		def = NXGetDefaultValue(APPNAME, "OnAutoLaunch");

		if (strcmp(def, "ExecuteAndQuit")==0)
			doLaunch();
		
		loadnib();
		if (strcmp(def, "Ask")==0)
		{
			int reply;
			loadnib();
			reply = NXRunAlertPanel(APPNAME, "Execute Launch script?",
					"OK", "NO", NULL);
			if (reply == NX_ALERTDEFAULT)
				[[NXApp delegate] executeLogin:NXApp];
		}
		
		if (strcmp(def, "Execute")==0)
		{
			[[NXApp delegate] executeLogin:NXApp];
		}
	}
	else
		loadnib();

	
	// If not autolaunched or if execution fails, run the application as normal 
	[NXApp run];
	[NXApp free];
	exit(0);
}
