// 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.


	2003-08-15 kio	fixed stdin/out/err redirection
*/

#define SAFE	2
#define	LOG 	1

#include "config.h"
#include <iostream>
#include <stdlib.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <termios.h>
#include "VScript.h"
#include "unix/file_utilities.h"
#include "ustring/sstring.h"
#include "Stream.h"
#define _include_version_as_source_
#include "version.h"
#include "token.h"


const char compiler[] =
#if defined(_METROWERKS)
	"Metrowerks"
#elif defined(_GCC)
	"gnu-cc"
#elif defined(_MPW)
	"MPW"
#else
	"unknown"
#endif
;

const char platform[] =
#if defined(_UNIX)
	#if defined(_LINUX)
		#if defined(_SUSE)
			"Unix-Linux-SuSE"
		#elif defined(_DEBIAN)
			"Unix-Linux-Debian"
		#elif defined(_REDHAT)
			"Unix-Linux-Redhat"
		#elif defined(_YELLOWDOG)
			"Unix-Linux-YellowDog"
		#else
			"Unix-Linux-unknown"
		#endif
	#elif defined(_BSD)
		#if  defined(_FREEBSD)
			"Unix-BSD-FreeBSD"
		#elif defined(_OPENBSD)
			"Unix-BSD-OpenBSD"
		#elif defined(_NETBSD)
			"Unix-BSD-NetBSD"
		#elif defined(_MACOSX)
			"Unix-BSD-MacOSX"
		#else
			"Unix-BSD-unknown"
		#endif
	#elif defined(_MINIX)
		"Unix-Minix"
	#elif defined(_SOLARIS)
		"Unix-Solaris"
	#else
		"Unix-unknown"
	#endif
#elif defined(_WINDOWS)
	"Windows"
#elif defined(_BEOS)
	"BeOS"
#elif defined(_MACINTOSH)
	"MacOS classic"
#else
	"unknown"
#endif
;

const char processor[] =
#if defined(_POWERPC)
	"PowerPC"
#elif defined(_M68K)
	"MC680x0"
#elif defined(_I386)
	"i386"
#elif defined(_ALPHA)
	"Alpha"
#elif defined(_SPARC)
	"Sparc"
#elif defined(_I386x64)
	"i386x64"
#else
	"unknown"
#endif
;

const char endian[] =
#if defined(_LITTLE_ENDIAN)
	"little endian (LSB first)"
#elif defined(_BIG_ENDIAN)
	"big endian (MSB first)"
#elif defined(_PDP_ENDIAN)
	"pdp endian (LSB first + MSW first)"
#else
	"unknown"
#endif
;

String	applName;
bool	verbose			= no;
Stream*	stdStream[3]	= { NULL,NULL,NULL };

static struct termios	old_stdin_termios;



/* ----	restore old settings for stdin ---------------------------
		sheduled via atexit()
*/
static void RestoreStdin ( void )
{
	XXLog("RestoreStdin() executed");

	char bu[]="\033[0m"; write(0,bu,4);			// reset text attributes
	tcsetattr(0,TCSADRAIN,&old_stdin_termios);	// drain output, then change
}


/* ---- show help summary -----------------------------------
		display optimized for 80 character terminals
*/
static void ShowHelp ( void )
{
	fputs( "\n"
"______________________________________________________________________________\n"
"vipsi - VIP script interpreter "_VERSION_" (c) 2001-2003 kio@little-bat.de\n"
"development release. please set your terminal to utf-8 and vt100.\n"
"see <http://vipsi.sourceforge.net> for latest documentation.\n"
"\n"
"vipsi -v        => verbose mode\n"
"vipsi -h        => print help screen\n"
"vipsi -t        => run internal test\n"
"vipsi -i file   => set stdin\n"
"vipsi -o file   => set stdout\n"
"vipsi -l file   => set stderr\n"
"\n"
"vipsi filename  => execute script.\n"
"vipsi           => interaktive shell. help available from within.\n"
"calc expression => calculate expression and display result.\n"
"______________________________________________________________________________\n"
"", stderr );
}



/* ---- program entry ---------------------------
*/
int main( int argc, cstr argv[] )
{	int   i;

	cstr stdinName  = NULL;
	cstr stdoutName = NULL;
	cstr stderrName = NULL;
	applName   		= argv[0];
	verbose    		= no;
	bool test       = no;
	ClearError();

	if (XXSAFE)
	{
		static uchar bu[16];
		for (int i=0;i<8;i++)
		{
			write_double(bu+i,123.456e78);
			TRAP(read_double(bu+i)!=123.456e78);
		}
	}

//	Loop: scan for options

	for ( i=1; i<argc; i++ )
	{
		cstr s = argv[i];
		if (!s||s[0]!='-') break;			// first non-option

		for ( int j=1; s[j]!=0; j++ )
		{
			switch(s[j])
			{
			case 'v':
				verbose=yes;
				continue;

			case 't':
				test=yes;
				continue;

			case 'i':
			{	if( ++i>=argc||stdinName ) goto h;
				stdinName = FullPath(argv[i]); if(Error()) goto x;
				int newfd = open(stdinName,O_RDONLY);
				if(newfd==-1) goto x;	// errno set
				if(close(0/*stdin*/)==-1) goto x;
				if(dup(newfd)!=0) { SetError("dup(fd(0)) failed"); goto x; }
				close(newfd);
			}	continue;

			case 'o':
			{	if( ++i>=argc||stdoutName ) goto h;
				stdoutName = FullPath(argv[i]); if(Error()) goto x;
				int newfd = open(stdoutName,O_WRONLY|O_CREAT|O_TRUNC,0660/*muss angegeben werden!*/);
				if(newfd==-1) goto x;	// errno set
				ClearError();			// errno=ENOENT if file did not exist!
				if(close(1/*stdout*/)==-1) goto x;
				if(dup(newfd)!=1) { SetError("dup(fd(1)) failed"); goto x; }
				close(newfd);
			}	continue;

			case 'l':
			{	if( ++i>=argc||stderrName ) goto h;
				stderrName = FullPath(argv[i]); if(Error()) goto x;
				int newfd = open(stderrName,O_WRONLY|O_CREAT|O_TRUNC,0660/*muss angegeben werden!*/);
				if(newfd==-1) goto x;	// errno set
				ClearError();			// errno=ENOENT if file did not exist!
				if(close(2/*stderr*/)==-1) goto x;
				if(dup(newfd)!=2) { SetError("dup(fd(2)) failed"); /* printing errorstr will probably fail... */ goto x; }
				close(newfd);
			}	continue;

			default:
			h:	ShowHelp();					// argv[] error => print help text
				return commandlineerror;	// and return error code, don't print error message
			}
		}
	}

	if(Error())
	{
x:		Log ( "\nvipsi: %s\n\n", ErrorStr() );
		return Error();
	}

// create standard streams
	stdinStream  = new Stream(0,stdinName ?stdinName :"stdin://");
	stdoutStream = new Stream(1,stdoutName?stdoutName:"stdout://");
	stderrStream = new Stream(2,stderrName?stderrName:"stderr://");
	if(Error()) goto x;

// run internal test ?
	if (test)
	{
		verbose = yes;

	// test the compiled code:
		ClearError();
		TestStringClass();
		if (Error()) Log("*** String Test error: %s ***\n\n",ErrorStr()); else LogNL();
		ClearError();

		TestVarClass();
		if (Error()) Log("*** Var Test error: %s ***\n\n",ErrorStr()); else LogNL();
		ClearError();
	}

	if (verbose)
	{
		Log("\n");
		Log( "Compiled with %s\n", compiler);
		Log( "Compiled for %s\n", platform);
		Log( "Running on a %s CPU\n", processor);
		Log( "Byte order is %s\n", endian);

		Log("\n");
		Log( "Memory access alignment is %s\n", _ALIGNMENT_REQUIRED ? "required" : "not required" );
		Log( "max. alignment is %i\n", _MAX_ALIGNMENT);

		Log( "%s alignments:\n", _ALIGNMENT_REQUIRED ? "Required" : "Preferred" );
		Log( "    short ....... %i\n", _SHORT_ALIGNMENT);
		Log( "    int ......... %i\n", _INT_ALIGNMENT);
		Log( "    long ........ %i\n", _LONG_ALIGNMENT);
		Log( "    llong ....... %i\n", _LONG_LONG_ALIGNMENT);
		Log( "    double ...... %i\n", _DOUBLE_ALIGNMENT);
		Log( "    pointer ..... %i\n", _POINTER_ALIGNMENT);

		Log( "sizeof(float)   = %i\n",   sizeof(float));
		Log( "sizeof(double)  = %i\n\n", sizeof(double));

	// info about current environment:
		Log("\n");
		Log("applName = %s\n", CString(applName) );
		Log("stdin    = %s\n", stdinName );
		Log("stdout   = %s\n", stdoutName);
		Log("stderr   = %s\n", stderrName);

		for (int j=0;j<3;j++)
		{
			if (stdStream[j]->GetType()!=s_tty) continue;
			uint rows,cols; TerminalSize ( j, rows, cols );
			Log( "Terminal size: rows,cols = %u,%u\n",rows,cols );
			break;
		}

		Log("\n");
		TRAP(Error());
	}

// setup tty
	if (stdinStream->GetType()==s_tty)
	{
		struct termios new_stdin_termios;
		XXXTRAP(stdinStream->GetFD()!=0);
		TRAP( tcgetattr(0,&old_stdin_termios) == -1 );	// for restore
		TRAP( tcgetattr(0,&new_stdin_termios) == -1 );	// for vipsi
		TRAP(Error());
		atexit(RestoreStdin);		// ***TODO*** also on error exit
		TRAP(Error());

		new_stdin_termios.c_lflag    &= ~ICANON;// noncanonical input: no wait for nl, no erase, no kill processing
		new_stdin_termios.c_lflag    &= ~ECHO;	// no echo on input
		new_stdin_termios.c_lflag    &= ~ECHONL;// also no echo for nl on input
		new_stdin_termios.c_cc[VMIN]  = 1;		// min. input bytes for read(); note: 0 does not work with FILE* !!
		new_stdin_termios.c_cc[VTIME] = 0/*1*/;  	// max. wait time in 0.1s for read(); 0==off
		TRAP ( tcsetattr(0,TCSADRAIN,&new_stdin_termios) );	// drain output, then change
		SetBlocking(0,yes);
		TRAP(Error());
	}

// Execute:
	if (i==argc)		// Shell
	{
		VScript().RunShell();
		return 0; /* ok */
	}

	else if ( applName.RightString(4)=="calc" )		// quick calculator
	{
		String s;
		for ( ; i<argc; i++ ) { s += argv[i]; s += " "; }
		VScript().RunCalc( s );
		return 0; /* ok */
	}

	else				// script, cgi-script
	{
		const int errno_notrepresentable  = 127;
		const int result_notrepresentable = 126;
		Var temp;
		Var* v = &temp;
		VScript si;
		si.RunScript( argv[i], argc-(i+1), argv+(i+1), v );
		if (Error()) return (uint)Error()<126 ? (uint)Error() : errno_notrepresentable;
		else   		 return v==NULL ? 0
						  	: v->IsNumber() && (uint)v->Value()<126 ?
							  (uint)v->Value() : result_notrepresentable;
	}
}


















