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

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

#include "Libraries/kio/kio.h"
#include "Libraries/unix/files.h"
#include "main.h"
#include "globals.h"
#include "IdfID.h"
#include "Names.h"
#include "Compiler/Compiler.h"
#include "Linker.h"
#include "Preprocessor/Preprocessor.h"
#include "Make.h"
#include "Targets/Target.h"
#include "utilities.h"
#include "FileInfo.h"


static bool	preprocess_only;// (don't compile)
static bool	compile_only;	// (don't assemble)
static bool	assemble_only;	// (don't link)
static bool	self_test;
static cstr optionstr = "";


/*	vcc -L path/to/libdir -I path/to/incdir -T path/to/tempdir -O path/to/outputdir [/path/to/]sourcefile.cc

	-L	if path/to/libdir is not an absolute path then the current working directory is used
	-I	if path/to/incdir is not an absolute path then the current working directory is used
	-T	if path/to/tmpdir is not an absolute path then the current working directory is used
	-O	if path/to/outdir is not an absolute path then the current working directory is used
	if path/to/sourcefile is not an absolute path then the current working directory is used

	if any path is not an absolute path then the current working directory is used

	output in output directory:

	/path/to/outputdir/	sourcefile.[asm|exe|…]			output file
						listings/sourcefile__xxx.txt	list output for compiling and linking "sourcefile.cc"
						listings/otherfile_xxx.txt		list output for compiling required "otherfile.cc"

	files in temp dir:

	/tempdir/vcc/cpu/	combinedOptionsString/path/to/sourcefile_xxx	preprocessed / precompiled / result file
						combinedOptionsString/path/to/otherfile_xxx		preprocessed / precompiled file
*/

static void showHelp()
{
	cstr cpus = "vcc";
	for (uint i=0; i<targeteers.count(); i++) { cpus = catstr(cpus, ",", targeteers.getKeys()[i]); }

	printf(
	//	"---------!---------!---------!---------!---------!---------!---------!---------!"
		"\n"
		APPL_LONG_NAME " " APPL_VERSION " " APPL_COPYRIGHT "\n"
		"  built by " BUILD_USER " on " BUILD_DATE " for " BUILD_TARGET ".\n"
		"  home: " myDomain "; send bugs to: " myEmail "\n"
	//	"  vcc <filename> <arguments>   compile <filename> and execute with <arguments>\n"
		"  vcc <options> <filename>     compile <filename>\n"
		"command:\n"
		"    -h                show help (this)\n"
		"    -i                show system info\n"
		"    -p                preprocess only, don't compile\n"
		"    -c                compile only, don't assemble\n"
		"    -a                compile and assemble, don't link\n"
		"general:\n"
		"    -v0|1|2           verbose\n"
	//	"    -d                debug\n"
		"    -t                test\n"
		"    -T<dirpath>       set temp dir\n"
		"    -O<dirpath>       set output dir\n"
		"compile:\n"
		"    --target=<name>   %s\n"
		"    -o0|1|2|s         optimize no|std|max|size\n"
		"    -D<name>[=<text>] define preprocessor value\n"
		"    -I<dirpath>       add header search path\n"
		"link:\n"
		"    -L<dirpath>       add library search path\n"
	//	"    -o=<filename>     set output file\n\n"
		,cpus );
}

static void showInfo()
{
	logline("\nvcc info:");
	logline("  version:    %s", APPL_VERSION);
	logline("  build date: %s", BUILD_DATE);
	logline("  invocation: %s", appl_path);
	logline("  num tokens: %u", uint(total_idf_ids));

	logline("\nhost info:");
	logline("  " _PLATFORM );
	logline("  cpu:     " _PROCESSOR ": %i cores", numCPUs());
	logline("  short:   %u bytes",uint(sizeof(short)));
	logline("  int:     %u bytes",uint(sizeof(int)));
	logline("  long:    %u bytes",uint(sizeof(long)));
	logline("  float32: %u bytes",uint(sizeof(float32)));
	logline("  float64: %u bytes",uint(sizeof(float64)));
	logline("  float128:%u bytes",uint(sizeof(float128)));
	logline("  size_t:  %u bytes",uint(sizeof(size_t)));
	logline("  byte order = " _BYTEORDER);

	#if _ALIGNMENT_REQUIRED
		logline("  alignment required:");
		logline("    short:   %u",(uint)_SHORT_ALIGNMENT);
		logline("    int:     %u",(uint)_INT_ALIGNMENT);
		logline("    long:    %u",(uint)_LONG_ALIGNMENT);
		logline("    llong:   %u",(uint)_LONG_LONG_ALIGNMENT);
		logline("    float64: %u",(uint)_DOUBLE_ALIGNMENT);
		logline("    float128:%u",(uint)_LONG_DOUBLE_ALIGNMENT);
	#else
		logline("  no alignment required");
	#endif

	logline("\navailable targets:");
	for (uint i=0; i<targeteers.count(); i++)
	{
		Target* target = targeteers.getItems()[i]();
		logline("  %s\t%s", target->name,target->descr);
		delete target;
	}

	logline("\ntarget info:");
	logline("  target      = %s", target->name);
	logline("  byte order  = %s", target->byteorder==byteorder_lohi ? "little endian (lsb first)" :
								  target->byteorder==byteorder_hilo ? "big endian (msb first)" : "undefined");
	logline("  bits/byte   = %u", uint(target->bpb));
	logline("  bits/char   = %u", uint(target->bpc));
	logline("  bits/short  = %u", uint(target->bps));
	logline("  bits/int    = %u", uint(target->bpi));
	logline("  bits/long   = %u", uint(target->bpl));
	logline("  bits/size_t = %u", uint(target->bpp));
	if(target->bpsf) logline("  bits/short float = %u", uint(target->bpsf));
	if(target->bpf)  logline("  bits/float       = %u", uint(target->bpf));
	if(target->bplf) logline("  bits/long float  = %u", uint(target->bplf));

	logline("\n");
}

static void parseArguments (int argc, char** argv)
{
	for (int i=0; i<argc;)
	{
		cstr opt = argv[i++];
		char c = *opt;
		if (c != '-')	// not an option
		{
			if (i == argc && !sourcefile) { setSourceFile(opt); return; }
			else throw AnyError("unknown option: \"%s\"", opt);
		}
		else opt++;

		// option: c == '-'

		if ((c=*opt++) == '-')	// longish option: "--xxx"
		{
			if (eq(opt,"verbose")) { verbose=1; continue; }
			if (eq(opt,"info")) { showInfo(); continue; }
			if (eq(opt,"help")) { showHelp(); continue; }
			if (eq(substr(opt,opt+4),"cpu="))    { setTarget(opt+4); continue; }
			if (eq(substr(opt,opt+7),"target=")) { setTarget(opt+7); continue; }
			else throw AnyError("unknown option \"%s\"", opt-2);
		}

		do		// short option(s): "-x" or "-xyz"
		{
			switch(c)
			{
			case 'a':
				assemble_only = true;	// don't link
				break;

			case 'c':
				compile_only = true;	// don't assemble
				break;

		//	case 'd':
		//		debug = true;
		//		break;

			case 'h':
				showHelp();
				break;

			case 'i':
				showInfo();
				break;

			case 'o':				// optimize code
				c = *opt++;
				optionstr = catstr(optionstr,"-o",charstr(c));
				if (c == 's') { optimize = 's'; break; }
				if (c >= '0' && c <= '9') { optimize = c - '0'; break; }
				throw AnyError("level of optimization expected");

			case 'p':
				preprocess_only = true;		// don't compile
				break;

			case 't':
				self_test = true;	// run self test
				break;

			case 'v':				// verbosity
				c = *opt++;
				if (c >= '0' && c <= '2') { verbose = c - '0'; break; }
				else { verbose = 1; opt--; break; }

			case 'D':	// -Dxxx[=yyy]		#define integer constant for preprocessor
			  {			// validate definition and add the string to argv_macros
				cptr p = opt;
				while (is_letter(*p) || *p == '_') { p++; }
				if (p == opt) throw AnyError("-D: macro name expected");		// no name

				if (*p == '(')
				{
					p++;
					while (*p != ')')
					{
						do
						{
							cptr p0 = p; while (is_letter(*p) || *p == '_') { p++; }
							if (p == p0) throw AnyError("-D: macro argument name expected");
						}
						while (*p++ == ',');
						p--;
					}
					p++;
				}

				if (*p == '=')    argv_macros = catstr(argv_macros,"#define ",substr(opt,p)," ",p+1,"\n");
				else if (*p == 0) argv_macros = catstr(argv_macros,"#define ",opt,"\n");
				else              throw AnyError("-D: '=' expected");

				optionstr = catstr(optionstr, "-D", replacedstr(opt,'/',':'));
				opt = "";		// opt -> char(0)
				break;
			  }

			case 'I':	// add #include header file dir
				if(i==argc) throw AnyError("-I: directory path expected");
				addIncludePath(argv[i++]);
				break;

			case 'L':	// add library search path
				if(i==argc) throw AnyError("-L: directory path expected");
				addLibraryPath(argv[i++]);
				break;

			case 'O':	// set output dir
				if(i==argc) throw AnyError("-O: directory path expected");
				setOutputDir(argv[i++]);
				break;

			case 'T':	// set temp dir
				if(i==argc) throw AnyError("-T: directory path expected");
				setTempDir(argv[i++]);
				break;

			default:
				throw AnyError("unknown option '%c'",c);
			}
		}
		while((c=*opt++));
	}
}

int main(int argc, char** argv)
{
	//openLogfile("/tmp/",LogRotation::DAILY,2,1);

// internal tests:

	xlogNl();
	assert(sizeof(errno) == 4);
	union { int64 l; float64 f; } z; z.l = 0; assert(z.f == 0.0);

// setup:

	appl_path	= fullpath(argv[0],yes,no);
	appl_name	= filename_from_path(appl_path);
	appl_ctime	= file_mtime(appl_path,1);

// parse command line arguments:

	try
	{
		parseArguments(argc-1,argv+1);
	}
	catch(AnyError& e)
	{
		logline("%s",e.what());
		showHelp();
		return 1;
	}

	if (!sourcefile)	// maybe called with -i etc.
	{
		return 0;
	}

	if (target == nullptr)
	{
		printf("no default target: use option --cpu");
		return 1;
	}

	if (!outputdir)
	{
		setOutputDir(directory_from_path(sourcefile));
	}

	// set list dir:
	{
		setListDir(catstr(outputdir,"listings/"));
	}

	// set temp dir:
	{
		if (!tempdir) tempdir = tempdirpath();
		if (!tempdir) tempdir = catstr(outputdir,"tmp/");

		// put stuff in sub folder:
		tempdir = catstr(tempdir,"vcc/",target->name);

		// add options as one subfolder:
		tempdir = catstr(tempdir,"/-o",charstr(char(optimize|0x30)));
		static_assert(0x30=='0' && ('s'|0x30)=='s',"");

		// add macros as 1 subfolder per macro:
		if(argv_macros)
		{
			Array<cstr> a; split(a,replacedstr(argv_macros,'/',':'));
			for(uint i=0;i<a.count();i++)
				tempdir = catstr(tempdir,"/",a[i]+8);	// without "#define "
		}
		setTempDir(tempdir);
	}

	if(verbose) logline("sourcefile = %s",sourcefile);
	if(verbose) logline("outputdir  = %s",outputdir);
	if(verbose) logline("listdir    = %s",listdir);
	if(verbose) logline("tempdir    = %s",tempdir);


// DOIT:

	try
	{
		if (self_test)
		{
			TODO();
		}

		Make make;
		if (preprocess_only)	{ make.preprocess(sourcefile,listdir); }
		else if (compile_only)	{ make.compile(sourcefile,listdir); }
		else if (assemble_only) { make.assemble(sourcefile,outputdir,listdir); }
		else					{ make.make(sourcefile,outputdir,listdir); }
	}
	catch(AnyError& e)
	{
		logline("exception: %s",e.what());
		return 2;
	}

	if (errors.count() == 0)
	{
		if(verbose) logline("no errors");
		return 0;
	}
	else
	{
		for(uint i=0; i<errors.count(); i++)
		{
			Error& error = errors[i];
			cstr file = included_files.fileForPos(error.pos).filepath;
			file = filename_from_path(file);
			uint line = included_files.lineForPos(&source[0],error.pos);
			printf("%s line %u: %s\n",file,line,error.msg);
		}

		printf("%u error%s\n", errors.count(), errors.count()==1?"":"s");
		return 1;
	}
}
























