
/*
 * MAIN.C
 *
 *  (C)Copyright 1987 Matthew Dillon, All rights reserved
 *
 *  Contains initialization and other stuff.  Note that there is no
 *  support for workbench startup.  This isn't simply a matter of
 *  setting up a window.... to get this baby to work from workbench we
 *  would need to simulate an entire CLI (proc->pr_CLI must be valid).
 *
 */

#include "shell.h"
#include <libraries/dosextens.h>
#include <stdio.h>

extern long SetSignal();

char Inline[256];
static long Orig_dir;

extern int Enable_Abort;

main(argc, argv)
short argc;
register char *argv[];
{
    char *prompt;
    struct Process *proc;
    register short i;

    Enable_Abort = 0;
    proc = (PROC *)FindTask(0);
    if (proc->pr_CLI == NULL)              /* sorry, no WB startup */
	exit(1000);
    Orig_dir = proc->pr_CurrentDir;
    CurrentDir(DupLock(Orig_dir));
    init_vars();
    init();
    seterr();
    do_cd(NULL, -1);
    for (i = 1; i < argc; ++i) {
	if (strcmp(argv[i], "-c") == 0) {
	    Inline[0] = '\0';
	    for (++i; i < argc; ++i) {
		if (*argv[i] == '\"') {             /* CLI quotes?   */
		    strcat(Inline, argv[i]+1);       /* remove quotes */
		    Inline[strlen(Inline)-1] = '\0';
		} else {
		    strcat(Inline, argv[i]);
		}
		if (i + 1 < argc)
		    strcat(Inline, " ");
	    }
	    exec_command(Inline);
	    main_exit(0);
	}
	strcpy (Inline, "source ");
	strcat (Inline, argv[i]);
	av[0] = "source";
	av[1] = argv[i];
	do_source (Inline, 0);
    }
    for (;;) {
	if ((prompt = get_var (LEVEL_SET, V_PROMPT)) == NULL)
	    prompt = "echo -n \"% \"";
	/*
	 *
	 *  Removed, WaitForChar() is buggy
	 *
	if (CHECKBREAK()) {
	    while (WaitForChar(Input(), 10))
	    gets(Inline);
	}
	 */

	++H_stack;
	++Exec_ignoreresult;
	exec_command (prompt);
	--Exec_ignoreresult;
	--H_stack;
	if (Quit)
	    main_exit(0);
	if (gets(Inline) == NULL) {
	    if (IsInteractive(Input()) && !S_ignoreeof)
		main_exit(0);
	    clearerr(stdin);
	}
	resetbreak();
	if (*Inline == '^')
	    hat_replace(Inline);
	if (*Inline)
	    exec_command(Inline);
    }
}

init_vars()
{
    if (IsInteractive(Input()))
	set_var (LEVEL_SET, V_PROMPT, "echo -n \"% \"");
    else
	set_var (LEVEL_SET, V_PROMPT, "");
    set_var (LEVEL_SET, V_HIST, "20");
    set_var (LEVEL_SET, V_PATH, "ram:,ram:c/,c:,df2:c/,df1:c/,df0:c/");
}

init()
{
    static char pipe1[32], pipe2[32];

    Cin = Input();
    Cout= Cerr = Output();
    Uniq= (long)pipe1;         /* address of some global variable */
    Pipe1 = pipe1;
    Pipe2 = pipe2;
    sprintf (pipe1, "ram:pipe1_%ld", Uniq);
    sprintf (pipe2, "ram:pipe2_%ld", Uniq);
}

main_exit(n)
{
    UnLock(CurrentDir(Orig_dir));
    do_cldres();
    exit (n);
}

docheckbreak()
{
    if (checkbreak()) {
	printf("^C\n");
	return(1);
    }
    return(0);
}

