/*
 * 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 U. Dominik Mueller 17-Feb-91
 *
 */

#include "shell.h"

static struct Window *getwindow(void);
static void add_residents(void);
static void exectimer(int stop);
char shellcompiled[]="Compiled: "__DATE__" "__TIME__" with "COMPILER"\n";
char shellname[]    ="Csh 5.19";
char shellversion[] ="519";
char shellvers[]    ="5.19";
char shellv   []    ="\0$VER: csh 5.1";
char shellctr []    ="CshCounter";
char shellres []    ="CshResident";
char shellthere[]   ="CshLoggedIn";

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

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",
	v_insert,   "1",
	"_terminal","",
	"_man",     "csh:csh.doc",
	"_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",
	"rx",   "RX",
	"manlist", "search -nl $_man \"    \"",
	NULL,   NULL
};

struct MsgPort *Console=(struct MsgPort *)-1;
long ExecTimer, ExecRC;

#ifdef LATTICE
ULONG stack=8192;
#endif

main(int argc, char *argv[])
{
	static ROOT locals;
	BPTR fh;
	int i, login=0;
	char buf[10];
	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(60);
		exit(0);
	}

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

	init_mbase();
	push_locals( &locals );
	initmap();

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

	IntuitionBase=(void*)ArpBase->IntuiBase;
	PatternBase  =OpenLibrary("pattern.library",5);

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

	if( !IsInteractive(Input())) {
		o_bground=1;
		Mycli->cli_Background=DOSTRUE;
	} else
		Mycli->cli_Background=DOSFALSE;

	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(shellres  ,buf,10)) o_resident=1;
	if (!Getenv(shellthere,buf,10)) login=1, Setenv(shellthere,"1");
	if ( Getenv(shellctr  ,buf,10)) i=atoi(buf);
	sprintf(buf, "%d", i+1);
	Setenv(shellctr, buf);
	Permit();

#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

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

	seterr(0);
	if (Myprocess->pr_CurrentDir == NULL)
		execute("cd :");
	set_cwd();

	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]=='-' && (index(argv[i],'a') || index(argv[i],'t')))
			o_nowindow=1;
		if (*argv[i]=='-' && index(argv[i],'n'))
			nologin=1;
	}

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

	if (!nologin ) {
/*
		if( exists("S:.cshinit"))
			execute("source S:.cshinit");
		if( exists("S:.cshrc"))
			execute("source S:.cshrc");
*/
		if( exists("S:.login"))
			execute("source S:.login");
	}

	for (i = 1; i < argc; ++i) {
		if (*argv[i]=='-') {
			char *str=argv[i]+1;
			for( ; *str; str++ ) {
				switch( *str) {
				case 'c':
				case 'C': execute( compile_av( argv, i+1, argc, ' ',*str=='C'));
				          main_exit(Lastresult); break;
				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 '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 '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( !isconsole(Input()))
		main_exit( Lastresult );

	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();
		exectimer(0);
		if (*Inline) ExecRC=exec_command(Inline);
		exectimer(1);
	}
}


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();
	if( PatternBase ) CloseLibrary( PatternBase );
	CloseLibrary((struct Library *)ArpBase);
	exit(n);
}


static void
exectimer(int stop)
{
	struct DateStamp dss;
	static long lasttime;
	long time;

	DateStamp(&dss);
	time=dss.ds_Minute*6000+2*dss.ds_Tick;   /* 2 = 100/TickPerSec   */
	if( stop )
		ExecTimer=time-lasttime;
	else 
		lasttime=time;
}



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(void)
{
	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;
	if( isconsole(Output()))
		Write(Output(),"",1);     /*    make window appear */ 
	if( Myprocess->pr_ConsoleTask ) {
		SendPacket(ACTION_DISK_INFO,args,(void *)Myprocess->pr_ConsoleTask);
		win=(struct Window *)infodata->id_VolumeNode;
		FreeMem(infodata,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];
};


static void
add_residents(void)
{
	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();
}

#ifdef LATTICE

int
setenv( char *var, char *val )
{
	char *buf=salloc(strlen(var)+strlen(val)+10);
	sprintf(buf, "%s=%s", var, val );
	Free(buf);
	return putenv(buf);
}

int
chkabort(void)
{
	return 0;
}

#endif

#ifdef _DCC
void 
swapmem(void *_s1, void *_s2, size_t _n)
{
	char t, *s1=_s1, *s2=_s2;
	int  i;

	for( i=0; i<_n; i++ )
		t=*s1; *s1++=*s2; *s2++=t;
}

int
setenv( char *var, char *val )
{
	BPTR fh;
	char buf[40];
	sprintf(buf,"ENV:%s",var );

	if( fh=Open(buf,MODE_NEWFILE) ) {
		Write(fh,val,strlen(val));
		Close(fh);
	}
}

int
rand()
{
	return 0;
}

_waitwbmsg() {return 0;};

#endif
