/*
 * MAIN.C
 *
 * Matthew Dillon, 24 Feb 1986
 * (c)1986 Matthew Dillon     9 October 1986
 *
 * Version 2.07M by Steve Drew 10-Sep-87
 * Version 4.01A by Carlo Borreo & Cesare Dieni 17-Feb-90
 * Version 5.00L by Urban Mueller 17-Feb-91
 *
 */

#include "shell.h"

void breakreset(void);
struct Window *getwindow (void);
struct RootNode2x *RootNode;

char shellname[]   ="CShell V5.15L";
char shellversion[]="515";
char shellvers[]   ="5.15";
char shellv   []   ="\0$VER: csh 5.1";
char shellctr []   ="CshCounter";
char shellres []   ="CshResident";

static void add_residents(void);

char *oldtitle;
char trueprompt[100];
char Inline[260];
struct IntuitionBase *IntuitionBase;
struct Window *Win;
struct ArpBase *ArpBase;
int    oldtaskpri=-999;
extern struct DosLibrary *DOSBase;
BPTR   OldCin;

static char *defset[]={
	v_histnum,  "0",
	v_titlebar, shellname,
	v_hist,     "50",
	v_lasterr,  "0",
	v_stat,     "0",
	v_path,     "RAM:,RAM:c,df0:c,df1:c,sys:system,csh:,s:",
	v_rxpath,   "REXX:",
	v_scroll,   "2",
	v_minrows,  "34",
	v_hilite,   "c7",
	v_lcd,      "",
	v_qcd,      "csh:csh-qcd",
	"_terminal","",
	"_man",     "csh:csh.doc",
	"_insert",  "1",
	"_version", shellversion,
	NULL,       NULL
};

static char *defalias[]={
	"cls",  "echo -n ^l",
	"dswap","cd $_lcd",
	"exit", "endcli;quit",
	"cdir", "%q cd $q; cls; dir",
	"q",    "quit",
	"manlist", "search -nl $_man \"    \"",
	NULL,   NULL
};

extern struct Library *DosBase;

struct MsgPort *Console=(struct MsgPort *)-1;

#ifdef LATTICE
ULONG stack=8192;
#endif

main(argc, argv)
char *argv[];
{
	static ROOT locals;
	BPTR fh;
	int i;
	char buf[10];
	struct Window *getwindow();
	char nologin=0;
#ifdef AZTEC_C
	extern int Enable_Abort;
	Enable_Abort = 0;
#endif

	MyMem=salloc(4);

	if( argc==0 ) {              /* Prevent starting from workbench */
		Delay(120);
		exit(0);
	}

	RootNode=(void *)DOSBase->dl_Root;
	push_locals( &locals );

	initmap();
	init_mbase();

	if(!(ArpBase=(struct ArpBase *)OpenLibrary("arp.library",34L)))
		{ printf("No arp library\n"); exit(0); }

	IntuitionBase=(struct IntuitionBase *)ArpBase->IntuiBase;

	if( ArpBase->DosBase->lib_Version >= 36 )
		o_kick20=1;
	set_var( LEVEL_SET, "_kick2x", (o_kick20) ? "1" : "0" );

	if( !IsInteractive(Input()))
		o_bground=1;
	set_var( LEVEL_SET, v_bground, (o_bground) ? "1" : "0" );

	if( fh=Open( o_kick20 ? "CONSOLE:" : "*", MODE_NEWFILE) ) {
		Console= ((struct FileHandle *)(4*fh))->fh_Type;
		Close(fh);
	}

	Forbid();
	i=0;
	if (Getenv(shellctr,buf,10L)) i=atoi(buf);
	if (Getenv(shellres,buf,10L)) o_resident=1;
	sprintf(buf, "%d", i+1);
	Setenv(shellctr, buf);
	Permit();

#ifdef isalphanum
	for( i='a'; i<='z'; i++ )
		isalph[i]=1;
	for( i='A'; i<='Z'; i++ )
		isalph[i]=1;
	for( i='0'; i<='9'; i++ )
		isalph[i]=1;
	isalph['_']=1;
#endif

#ifdef AZTEC_C
	stdin->_flags	|= _IONBF;	/* make sure we're set as an unbuffered tty */
	stdout->_flags	|= _IONBF;	/* in case of redirection in .login */
	Close( (BPTR)_devtab[2].fd);
	_devtab[2].mode |= O_STDIO;
	_devtab[2].fd = _devtab[1].fd;	/* set stderr to Output() otherwise */
					/* don't work with aux driver */
#else
	/* if( setvbuf( stdout,NULL,_IOLBF,BUFSIZ )) exit(20); */
	/* setnbf( stdout ); */
	/* Close( _ufbs[2] ); */
	/*_ufbs[2]=_ufbs[1]; */
	/* setnbf( stderr ); */
#endif

	Myprocess = (struct Process *)FindTask(0L);
	OldCin    = Myprocess->pr_CIS;
	Mycli=(struct CommandLineInterface *)((long)Myprocess->pr_CLI << 2);

	if( !o_nowindow && (Win=getwindow()) && isconsole(Input())) {
		oldtitle=(char *)(Win->Title);
		set_menu();
	}

	sprintf(buf,"%ld",Myprocess->pr_TaskNum);
	set_var(LEVEL_SET, "_clinumber", buf);

	seterr(0);
	if (Myprocess->pr_CurrentDir == NULL)
		do_cd("x :");
	else
		do_pwd(NULL);

	o_nowindow= 1;

	set_var(LEVEL_SET,v_prompt, (isconsole(Input())) ? "%c%p> ":"");
	for( i=0; defset[i]; i+=2 )
		set_var( LEVEL_SET, defset[i], defset[i+1] );
	for( i=0; defalias[i]; i+=2 )
		set_var( LEVEL_ALIAS, defalias[i], defalias[i+1] );

	o_nowindow= 0;
	o_internal= 1;

	for (i = 1; i < argc; ++i) {
		if (*argv[i]=='-') {
			char *str=argv[i]+1;
			for( ; *str; str++ ) {
				switch( *str) {
				case 'k': set_var(LEVEL_SET,v_nobreak,"1"); break;
				case 'i': if( str[1]=='0' ) str++, o_internal=0; break;
				case 'r': add_residents(); break;
				case 'v': Verbose=1; set_var(LEVEL_SET,v_verbose,"hs"); break;
				case 'n': nologin=TRUE;    break;
				case 'b': oldtaskpri=Myprocess->pr_Task.tc_Node.ln_Pri;
				          SetTaskPri( &Myprocess->pr_Task, -1 ); break;
				case 'f': oldtaskpri=Myprocess->pr_Task.tc_Node.ln_Pri;
				          SetTaskPri( &Myprocess->pr_Task,  1 ); break;
				case 'c': Inline[0] = ' '; Inline[1] = '\0';
				          while (++i < argc)
				              { strcat(Inline,argv[i]); strcat(Inline," "); }
				          execute(Inline);
				          main_exit(Lastresult); break;
				case 'a': o_nowindow= o_noraw= 1; 
				          set_var( LEVEL_SET, v_hilite, "" ); break;
				case 't': o_nowindow= o_vt100= o_nofastscr= 1;
				          set_var( LEVEL_SET, v_hilite, "r" );
				          set_var( LEVEL_SET, v_noreq, "1" );
				          set_var( LEVEL_SET, "_terminal", "1" );
				          set_var( LEVEL_ALIAS, "cls", "e -n ^[[0\\;0H^[[J" );
				          break;
				case 's': if( o_kick20 ) {
				              struct RootNode2x *root=(void *)DOSBase->dl_Root;
				              root->rn_Flags|=1<<24;
				          } break;
				}
			}
		} else {
			sprintf (Inline, "source %s",argv[i]);
			execute (Inline);
		}
	}

	if (!nologin && exists("S:.login")) execute("source S:.login");

	for (;;) {
		if (breakcheck())
			while (WaitForChar(Input(), 100L) || CHARSWAIT( stdin ))
				gets(Inline);
		clearerr(stdin);  /* prevent acidental quit */
		exec_every();
		update_sys_var(v_titlebar);
		update_sys_var(v_prompt);
		breakreset();
#if RAW_CONSOLE
		if (Quit || !rawgets(Inline, disable ? "_ " : trueprompt)) main_exit(0);
#else
		printf("%s", disable ? "_ " : trueprompt);
		fflush(stdout);
		if (Quit || !gets(Inline)) main_exit(0);
#endif
		breakreset();
		if (*Inline) exec_command(Inline);
	}
}

void
main_exit(n)
{
	int i;
	char buf[10];

	Getenv(shellctr,buf,10L);
	i=atoi(buf);
	sprintf(buf,"%d",i-1);
	Setenv(shellctr, buf);
	if( oldtitle )
		SetWindowTitles(Win,oldtitle,(char *)-1);
	if( oldtaskpri != -999 )
		SetTaskPri(&Myprocess->pr_Task,oldtaskpri);
	for (i=1; i<MAXMYFILES; i++) myclose(i);
	remove_menu();
	CloseLibrary((struct Library *)ArpBase);
	exit(n);
}

int
breakcheck()
{
	return !o_nobreak && SetSignal(0L,0L) & SIGBREAKF_CTRL_C;
}

void
breakreset()
{
	SetSignal(0L, SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_D);
}

dobreak()
{
	if (breakcheck()) { printf("^C\n"); return(1); }
	return(0);
}

/* this routine causes manx to use this Chk_Abort() rather than it's own */
/* otherwise it resets our ^C when doing any I/O (even when Enable_Abort */
/* is zero).  Since we want to check for our own ^C's			 */

long
Chk_Abort()
{
	return(0);
}

void
_wb_parse()
{
}

do_howmany()
{
	char buf[10];

	Getenv(shellctr, buf, 10L);
	printf("Shell(s) running: %s\n",buf);
	return 0;
}

static struct Window *
getwindow()
{
	struct InfoData *infodata;
	struct Window *win;
	long args[8];

	if( o_nowindow )
		return NULL;
	infodata=(void *)SAllocMem((long)sizeof(struct InfoData),MEMF_CLEAR|MEMF_PUBLIC);
	args[0]=(long)infodata >> 2;
	Write(Output(),"",1);     /*    make window appear */ 
	SendPacket(ACTION_DISK_INFO,args,(void *)Myprocess->pr_ConsoleTask);
	win=(struct Window *)infodata->id_VolumeNode;
	FreeMem(infodata,(long)sizeof(struct InfoData));
	if( win==NULL )
		o_nowindow=1;
	newwidth();
	return win;
}


extern struct DosLibrary *DOSBase;

struct ResidentList {
	BPTR rl_Next;
	LONG rl_UseCount;
	BPTR rl_SegList;
	char rl_SegName[1];
};


void
add_residents()
{
	char buf[80], *g, *p, c;
	struct RootNode *Node;
	struct DosInfo  *Info;
	struct ResidentList *res;
	struct ResidentProgramNode *rpn;

	if( o_kick20 || ArpBase->ResidentPrgList )
		return;

	Forbid(); 
	Node=(struct RootNode *)DOSBase->dl_Root;
	Info=(struct DosInfo  *)(Node->rn_Info*4);
	res=(struct ResidentList *)((long)Info->di_NetHand*4);

	for( ; res; res=(struct ResidentList *)((long)res->rl_Next*4) ) {
		g=res->rl_SegName, p=buf;
		for( c=*g++; c>0; --c ) *p++=*g++;
		*p=0;
		if( res->rl_UseCount>=0 )
			res->rl_UseCount++;
		else
			continue;
		if(rpn=AddResidentPrg( res->rl_SegList, buf))
			rpn->rpn_Usage++;
	}
	Permit();
}

#ifndef AZTEC_C

char *
rindex(char *s, int c)
{
	char *r;

	for( r=NULL; *s; s++ )
		if( *s==c )
			r=s;
	return r;
}

int
setenv( char *var, char *val )
{
	char buf[300];
	sprintf(buf, "%s=%s", var, val );
	return putenv( buf );
}

int
chkabort(void)
{
	return 0;
}

#endif
