// utf-8

/*	Copyright  (c)	Günter Woigk   2001-2003
  					mailto:kio@little-bat.de

	This file is free software

 	This program is distributed in the hope that it will be useful,
 	but WITHOUT ANY WARRANTY; without even the implied warranty of
 	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  

 	Permission to use, copy, modify, distribute, and sell this software and
 	its documentation for any purpose is hereby granted without fee, provided
 	that the above copyright notice appear in all copies and that both that
 	copyright notice and this permission notice appear in supporting
 	documentation, and that the name of the copyright holder not be used
 	in advertising or publicity pertaining to distribution of the software
 	without specific, written prior permission. The copyright holder makes no
 	representations about the suitability of this software for any purpose.
 	It is provided "as is" without express or implied warranty.

 	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 	CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
 	DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
 	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 	PERFORMANCE OF THIS SOFTWARE.

	2002-04-28 kio	changed Stream io[] to Stream* io[] to allow use of subclasses of Stream
					added OpenStream() and CloseStream()
	2003-07... kio	changes to use UCS4String library
*/


#define SAFE 3
#define LOG  2

#include "config.h"
#include <iostream>
#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/ioctl.h>
#include <termios.h>
#include "unix/file_utilities.h"
#include "unix/os_utilities.h"
#include "VScript.h"
#include "var/var.h"
#include "SystemIO.h"
#include "compress/freeze.h"
#include "token.h"
#include "Stream.h"
#include "version.h"

extern char **environ;		// required by: Mac OSX


// dummy stream with neither input nor output
// we use no_io instead of NULL for unused slots in io[]
// so that all slots in io[] can be valid streams
// eliminating the need for frequent checks for NULL
static Stream no_io;
	


/* ----	setup new VScript instance -------------------------------------
*/
VScript::VScript ( )
{
	XXXTRAP(tokens>256);
	XXXTRAP(NELEM(io)!=max_streams);
	XXXTRAP(NELEM(std_io)!=max_streams);
	XXXTRAP(no_io.IsOpenIn());
	XXXTRAP(no_io.IsOpenOut());
	ClearError();

// stream:
	std_io[0]	= stdinStream;
	std_io[1]	= stdoutStream;
	std_io[2]	= stderrStream;
	for (int i=3;i<max_streams;i++) std_io[i] = &no_io;
	memcpy ( io, std_io, sizeof(io) );
	stream	= 2;

// variables:
	globals	= new Var("globals",isList);
	locals	= globals;
	proc	= NULL;
}


/* ----	destructor --------------------------------------------------------------
		delete dynamically allocated memory
*/
VScript::~VScript()
{
	delete globals;
	for (int i=0;i<max_streams;i++) if (io[i]!=std_io[i]) delete io[i];
}


/* ----	select stream ---------------------------------------------------
		parse script for '#' stream identifier and set 'stream'
		if no stream identifier follows, the supplied dflt_stream is used
		optionally skip ',' after '#'
		in:		dflt_stream must be valid
		out:	'stream' always set to valid stream
		used in: 'open', 'put', 'get', 'log', 'close', 'pwd' et.al.
*/
uchar* VScript::SetStream ( uchar* ip, uint dflt_stream, bool expectkomma )
{
	XXTRAP( dflt_stream>=max_streams );
	stream = dflt_stream;

	if (*ip==tHASH)
	{
		Var temp; Var*v=&temp;
		ip = NumValue(ip+1,v,pUna);
		uint n = (uint)v->Value();
		if ( n>=max_streams ) { SetError( Using("maximum stream number is %i",max_streams-1) ); }
		if (expectkomma) ip = Expect(ip,tKOMMA);
		if (NoError()) stream = n;
	}
	
	return ip;
}


/* ----	close current stream -------------------------------------
		close file, delete Stream
		restore standard stream for io[0..2]  ((0..2 are never really closed))
		note: closing a stream may fail, but the stream is deleted in any case.
			  flush output before closing if this risk is a problem.
*/	
void VScript::CloseStream ( )
{
	if(Error()) return;
	uint n = stream;
	XXTRAP(n>=max_streams);

// dont close the default stream:
	if (io[n]==std_io[n]) { SetError(streamnotopen); return; }

// close stream
	delete io[n];
	io[n]=std_io[n];
}


/* ----	open current stream ---------------------------------------
		open current stream which must be unused
*/
void VScript::OpenStream ( cstr fname, int flags )
{
	if(Error()) return;
	uint n = stream;			// speed
	XXTRAP(n>=max_streams);

// don't open an already open stream:
	if (io[n]!=std_io[n]) { SetError(streamopen); return; }

// open stream
	io[n] = new Stream(fname,flags);
	if (Error()) CloseStream();
}


/* ----	check whether var can be deleted --------------------------------
		the following vektor variables must not be deleted or assigned a new value:
		- globals & parents
		- locals & parents
		- proc & parents
		call this test before deleting a vektor variable
		or before assigning a new value.
		raise error if variable is in use.
*/
bool VScript::TrapVarInUse ( Var* v )
{
	if (v->IsList())
	{
		if (v==globals) goto x;
		if (locals!=globals && v->Contains(locals) ) goto x;
		if ( v->Contains(proc) ) goto x;
		return no;
	}
	if (v!=proc) return no;

x:	SetError( variableinuse,String("Variable ")+ToQuoted(v->Name())+" is in use" );
	return yes;
}



void VScript::GetCGIArguments()
{	str gm,ga,gw,gn;
	if( (gm=getenv("REQUEST_METHOD")) )
	{
		if( SameStr(gm,"GET") && (ga=getenv("QUERY_STRING")) && *ga )
		{
			ga = DupStr(ga);	// 'GET' arguments
		}
		else if ( SameStr(gm,"POST") && (ga=getenv("CONTENT_LENGTH")) && *ga )
		{
			uint n; for( n=0; _is_dec_digit(*ga); ga++ ) { n = n*10+*ga-'0'; }
			if( *ga || n>100000 || n==0 ) return;		// bogus/no args
			ga = QString(n);
			read ( 0, ga, n );
		}
		else
		{
			return; 		// unknown/bogus request method
		}

		while(ga)
		{
			gw = ga;									// next word
			ga = strchr(ga,'&'); if (ga) *ga++ = 0;		// remaining arguments

			gn = gw;									// current argument name
			gw = strchr(gw,'='); 						// current argument value
			if (gw) *gw++ = 0; else { gw=gn; gn=""; }

			for( char c=1,*q=gw,*z=gw; c; z++,q++ )
			{
				c=*q; if(c=='+') c=' ';
				if( c=='%' && _is_hex_digit(q[1]) && _is_hex_digit(q[2]) )
				{ c = _digit_value(q[1])*16 + _digit_value(q[2]); q+=2; }
				*z=c;
			}

			globals->AppendItem(new Var(gn,gw));
		}
	}
}


static void PutPadded ( Stream*s, cstr t )
{
	String z(t);
	s->PutNL();
	s->PutString( VT_Colored(z+SpaceString(79-z.Len()), VT_Normal, VT_Color(VT_Yellow|VT_Bright)) );
}

void ShowHelp(Stream*s)
{
	ClearError();
	int cols = s->GetType()==s_tty ? TerminalCols(s->GetFD()) : 80; if(cols>80) cols=80;
	XXTRAP(Error());	// errno

	s->ClearError();	// Stream
	s->ClearAttr();

	PutPadded( s, 		"vipsi - VIP Script Interpreter "_VERSION_" (c) 2001-2003 kio@little-bat.de" 	);
	PutPadded( s, 		"development release. please set your terminal to utf-8 and vt100." 			);
	PutPadded( s, 		"see <http://vipsi.sourceforge.net> for latest documentation." 					);
	s->PutNL();
	PutPadded( s, 		"        vipsi is waiting for your commands." 									);
	PutPadded( s, 		"        type an expression to calculate the result." 							);
	PutPadded( s, Using("        type «%s» for a list of words.",			 CString(TokenName(tWORDS))));
	PutPadded( s, Using("        type «%s \"foo\"» for info on word «foo».", CString(TokenName(tINFO)))	);
	PutPadded( s,		"        use «pd_up» and «pd_dn» for history." 									);
	PutPadded( s,		"        type ctrl-D to quit." 													);
	if (verbose)
	PutPadded( s, Using("        vipsi knows &i words.", int(tokens)) 									);
	s->PutNL();
	s->PutNL();

	XXTRAP(s->GetError());
	ClearError();
}


/* ----	parse script file --------------------------
		may be called recursively to include files
		returned Var* v may be set to NULL for 'no value'
*/
void VScript::Run ( cString& filename, Var*& v )
{	ptr	 ibu = NULL;		// input file buffer
	long ilen = 0;			// input file length

	if (Error()) return;

#if 0
// directory:
	DIR* dir = opendir(filename);
	errno = ok;

	if (dir)
	{
		if (verbose) Log( "include dir \"%s\"\n", filename );
		readdir(dir);	// skip "./"
		readdir(dir);	// skip "../"

		cstr dirname = filename;
		if (LastChar(dirname)!='/') dirname = CatStr(dirname,"/");
		dirname = NewCopy(dirname); if (!dirname) SetError(outofmemory);

		while(!errno)	// loop for dirname/*
		{
			struct dirent* d = readdir(dir);
			if(!d) break;
			if (!SameStr(LowerStr(RightStr(d->d_name,3)),".vs")) continue;
			filename = NewCopy( CatStr(dirname,d->d_name) ); if (!filename) SetError(outofmemory);
			Run(filename);
			delete[] filename;
		}

		closedir(dir);
		delete[] dirname;
		return;
	}
#endif

// load script
	FILE* ifile = fopen(filename.CString(),"r");
	if (!ifile) { ForceError( Using( "open %s: %s", filename.ToQuoted().CString(), ErrorStr() ) ); return; }
	long type = ClassifyFile(ifile);

// dir:
	if(type==s_dir)
	{
		SetError( Using( "can't parse directory  %s", filename.ToQuoted().CString() ) );
		goto x;
	}

// tty, pipe, unkn: read until eof
	else if (type!=s_file)
	{
		if (verbose) Log( "include pipe/tty/unkn %s\n", filename.ToQuoted().CString() );
		SetError( "include pipe, tty or other non-file not yet supported" );
		goto x;
	}

// file:
	else
	{
		if (verbose) Log( "include file %s\n", filename.ToQuoted().CString() );
		ilen = FileLength(ifile); if (ilen==0) goto x;
		ibu  = new char[ilen+1]; if(!ibu) { SetError(outofmemory); goto x; }
		long n = fread(ibu,ilen,1,ifile);
		if (n!=1) { ForceError( Using( "read %s: %s", filename.ToQuoted().CString(), ErrorStr() ) ); goto x; }
		ibu[ilen]   = 0;		// end stop

	// convert line breaks to nl
		{
			ptr z = ibu;
			ptr e = ibu+ilen;
			while (z<e)
			{
				uchar c = *z++;
				if (c>13) continue;
				if (c!=0&&c!=10&&c!=13) continue;
				z[-1] = nl;
				if (c==0) continue;
			//	if (z==e) continue;			not necc.: *e=0
				if (c+*z!=23) continue;

				// DOS text file detected: cr+lf -> nl  =>  text size shrinks, text moves
				*--z=c;
				for ( ptr q=z; q<e; )
				{
					c = *q++;
					if (c!=10&&c!=13) { *z++ = c; continue; }	// move char
					q += c+*q==23; *z++ = nl;					// replace line break
				}
				e = z;
			}
			ilen = z-ibu;
		}

	// tokenize script
		Var myproc(filename,isProc);
		long idx_io=0;
		uchar* ip;
		myproc.Proc() = Tokenize ( String((cUTF8CharPtr)ibu,ilen), idx_io );

	// execute script
		if (NoError())
		{
			ip = Execute ( myproc, v );
			idx_io = ip-(uptr)myproc.Proc().Text();
			if(Error())
			{
				PushError();
				Tokenize ( String((cUTF8CharPtr)ibu,ilen), idx_io );	// find src position
				PopError();
			}
		}

	// error ?
		if(Error())
		{
			stderrStream->PutNL();
			stderrStream->PutString( VT_Colored(String("error: file ")+ToQuoted(filename),VT_Red) );
			stderrStream->PutNL();

			uint row=0,col=0;
			cptr q=ibu,e=ibu+idx_io;
			while (q&&q<e) { row++; col=e-q; q=(cptr)memchr(q,nl,col); if(q)q++; }

			String msg = SpaceString(7)+ErrorString()+" at row "+NumString(row) + ", col " + NumString(col+1);
			stderrStream->PutString( VT_Colored(msg,VT_Red) );
			stderrStream->PutNL();
		}
	}

// clean up
x:	delete[] ibu;
	fclose(ifile);
}


/* ---- run script -------------
		stream '0,1,2 = stdin/out/err
		sets/clears errno
		returned Var* v may be set to NULL for 'no value'
*/
void VScript::RunScript ( cString& script, int argc, cstr argv[], Var*& v )
{
	for ( int i=0; i<argc; i++ ) globals->AppendItem(new Var(argv[i]));
	GetCGIArguments();
	Run(script,v);
}


/* ---- run in shell mode -------------
		stream '0,1,2 = stdin/out/err
		sets/clears errno

		creates a copy of stdin for interactive input _and_ output
		stream 0 is used for get and may be changed without affecting shell io
		stream 1 is solely used for put
		stream 2 is solely used for log
*/
void VScript::RunShell ( )
{
	XXTRAP(Error());

// own reference to stdinStream => the user can "open#0,.."
// own copy of the stdinStream  => preserve our Stream settings
	XXXTRAP(stdinStream->GetFD()!=0);
	Stream term(0,stdinStream->GetPath());
	XXTRAP(term.GetType()!=s_tty);
	XXTRAP(!term.IsOpenIn());
	XXTRAP(!term.IsOpenOut());
	//defaults are all good:
	//term.ClearGetStoreCtls();
	//term.ResetGetStops();
	//term.SetConversion(utf8_noconv);
	//term.SetTimeoutIn(0);
	//term.SetTimeoutOut(0);

	term.PutString("\033%G");		// select UTF-8 character set
	ShowHelp(&term);
	XXXTRAP(Error());

	Var history(isList);
	Var myproc ( "shell", isProc );
	long editlastitem = 0;

// test for xterm
	cstr s;
	for( uint i=0; (s=environ[i]); i++ ) { if (memcmp(s,"TERM=",5)==0) break; }
	bool xterm = s && strcmp(s+5,"xterm")==0;

// doit:
	for(;;)
	{
		ClearError();

		term.PutString("vipsi> ");
		if (xterm) term.SetFGColor(VT_Blue); else term.SetBold();
		if (term.GetError()) break;
		String s = term.Input(history,editlastitem);
		if (term.GetError()) break;
		if (xterm) term.SetFGColor(VT_Normal); else term.SetBold(0);
		if (term.GetError()) break;

		Var temp;		// scratch for Value()
		Var* v = &temp;
		long idx_io=0;
		myproc.Proc() = Tokenize ( s, idx_io );
		XXTRAP( (idx_io==0)!=(NoError()) );

		if (NoError())
		{
			term.PutSpaces(2); if(term.GetError()) break;
			uptr ip = Execute(myproc,v); if (Error()==errEOF) ClearError();

			if (Error())
			{
				idx_io = ip-(uptr)myproc.Proc().Text();
				PushError();
				Tokenize(s,idx_io);
				PopError();
			}
		}

		if (Error())
		{
			term.PutNL();
			term.PutString( VT_Colored( String("*****  ")+ErrorString(), VT_Red) );
			editlastitem = idx_io?idx_io:1;
		}
		else
		{
			if (v) term.PutString( String("   = ")+v->ToString(yes,DisassString) );
			editlastitem = 0;
		}
		term.PutNL();
	}

	term.PutString("\nvipsi: have a nice day. ;-)\n\n");
	ClearError();
}


/* ---- quick calculate & print -------------
		stream '0,1,2 = stdin/out/err
		sets/clears errno
*/
void VScript::RunCalc ( cString& s )
{
	XXXTRAP(Error());

	Var myproc( "calc", isProc );
	long idx_io=0;
	myproc.Proc() = Tokenize ( s, idx_io );

	Var  temp;
	Var* v = &temp;

	if (NoError()) { Execute(myproc,v); if (Error()==errEOF) ClearError(); }
	if (!v) { v=&temp; temp=""; }

	if (Error()) stderrStream->PutString( VT_Colored(String("error: ")+ErrorString(),VT_Red) + nl );
	else stdoutStream->PutString( String(" = ") + v->ToString(yes,DisassString) + nl );
}






