/* File: NISave.m - (Interactive) Unix shell version of NISavePanel
 *
 * 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.
 */

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

#import <nikit/NISavePanel.h>

#define USAGE "\
usage: %s [-d directory] [-t title] [-p prompt] [-f directory] [-i icon] [-V] [-H]\n"

#define HELP "\
options:\n\
 -d directory netinfo directory\n\
 -t title     set title\n\
 -p prompt    set prompt\n\
 -f directory set initial directory\n\
 -i iconfile  pathname of application icon to use (default none)\n\
 -V           print version string and exit\n\
 -H           this help\n\
"

#define SEPARATOR "/"

const char *fullPath(const char *parent, const char *name)
{
	static char buffer[MAXPATHLEN];

	if(parent == NULL) return name;

	if(strcmp(strcpy(buffer, parent), SEPARATOR) != 0) (void) strcat(buffer, SEPARATOR);

	return strcat(buffer, name);
}

void main(int argc, char *argv[])
{
	const char *iconFile = NULL;
	const char *title = NULL, *prompt = NULL, *path = NULL, *string = "";
	int option, status = EXIT_SUCCESS;

	NXApp = [Application new];
	argc = NXArgc, argv = NXArgv;	// Application may munch options.

	while ((option = getopt(argc, argv, "d:t:p:f:i:VH")) != EOF)
		switch (option) {
		case 'd': path = optarg; break;
		case 't': title = optarg; break;
		case 'p': prompt = optarg; break;
		case 'f': string = optarg; 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();

	{
		int flags, context = [NXApp activateSelf:YES];
		NISavePanel *panel = [NISavePanel new];

		if (prompt != NULL) [panel setListTitle:(char *) prompt];
		if (title != NULL) [panel setPanelTitle:(char *) title];
		if (path != NULL) [panel setStartingDomainPath:path];

		if ((flags = [panel runModalWithString:(char *) string]) == NX_OKTAG)
			(void) puts(fullPath([panel domain], [panel directory]));
		else status = flags;

		[panel free];

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

	[NXApp free];

	exit(status);
}
