/* File: NILogin.m - (Interactive) Unix shell version of NILoginPanel
 *
 * By: Christopher Lane (lane@sumex-aim.stanford.edu)
 *
 * Date: 10 November 1992
 *
 * Modified:
 *	[17-Feb-96 TRH] Fix for Application option munching (like -NXHost).
 *	[15-Mar-96 TRH] add -V -H -i options; add EditMenu keyEquiv support.
 *
 * Copyright: 1991 & 1992 by The Leland Stanford Junior University.
 * This program may be distributed without restriction for non-commercial use.
 *
 * Warning: This code doesn't work, NILoginPanel doesn't perform as advertised.
 */

#define USES_APPICON
#define USES_KEYEQUIV
#import "ShellPanel.h"

#import <nikit/NIDomain.h>
#import <nikit/NILoginPanel.h>

#define DOMAIN "."
#define INSTRUCTION "This change to the NetInfo database requires privilege, please log in as an authorized user."
#define USER "root"

#define USAGE "\
usage: %s [-d domain] [-u user] [-p prompt] [-b] [-i icon] [-V] [-H]\n"

#define HELP "\
options:\n\
 -d domain    set netinfo domain (default \""DOMAIN"\")\n\
 -u user      set user (default \""USER"\")\n\
 -p prompt    set prompt\n\
 -b           allow user to be edited\n\
 -i iconfile  pathname of application icon to use (default none)\n\
 -V           print version string and exit\n\
 -H           this help\n\
"


void main(int argc, char *argv[])
{
	const char *iconFile = NULL;
	ni_status nstatus;
	id panel, domain;
	BOOL enableUser = YES;
	ni_name domainName = DOMAIN;
	int context, option, status = EXIT_SUCCESS;
	const char *userName = USER, *instruction = INSTRUCTION;

	context = [(NXApp = [Application new]) activateSelf:YES];
	argc = NXArgc, argv = NXArgv;	// Application may munch options.

	while ((option = getopt(argc, argv, "d:u:p:bi:VH")) != EOF)
		switch (option) {
		case 'd': domainName = (ni_name) optarg; break;
		case 'u': userName = optarg; break;
		case 'p': instruction = optarg; break;
		case 'b': enableUser = NO; break;
		case 'i': iconFile = optarg; break;
		case 'V': status = EXIT_VERSION; break;
		case 'H': status = EXIT_HELP; break;
		default : status = EXIT_USAGE;
		}
	if (optind < argc) status = EXIT_USAGE;

	HandleUsageHelpVersion(status, USAGE, HELP);

	SetAppIconToFile(iconFile);
	ProvideKeyEquivalents();

	panel = [NILoginPanel new];
	domain = [[NIDomain alloc] init];

	if ((nstatus = [domain setConnection:domainName]) != NI_OK) {
		(void) fprintf(stderr, "%s\n", ni_error(nstatus));
		status = EXIT_FAILURE;
	}
//	else if ([panel runModal:NXApp inDomain:[domain getDomainHandle]])
	else if ([panel runModal:NXApp inDomain:[domain getDomainHandle] withUser:userName withInstruction:instruction allowChange:enableUser])
		status = ([panel isValidLogin:NXApp]) ? EXIT_SUCCESS : EXIT_FAILURE;
	else status = EXIT_FAILURE;

	[panel free];
	[[domain disconnectFromCurrent] free];

	if (context) (void) [NXApp activate:context];

	[NXApp free];

	exit(status);
}
