/*
 * valabuild.vala
 * 
 * Copyright 2018-2021 Olivier Lecointre <olivier[at]cadexis[dot]com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * 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.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not see <http://www.gnu.org/licenses/>.
 * 
 */

//Example of valac commands
//valac --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala
//valac --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala
//valac --pkg gtk+-3.0 --pkg gmodule-2.0 --vapidir=../lib -X -I../lib -X -L../lib --pkg libgtkformhelper -X -lgtkformhelper -o valaman  valaman.vala testwin.vala --pkg libxml-2.0 --pkg libvala-0.26 --vapidir=/usr/local/share/vala-0.26/vapi
//export LD_LIBRARY_PATH=/home/olivier/vdocs/Projects/vala/lib

using Xml;
using Xml.XPath;

public class ValaBuild : GLib.Object
{
	public const string version = "0.1";
	public const string copyright = "2018-2021 Cadexis Ltd";
	
	//Combines 2 parts of directories, if path 2 is not absolute
	private string combine(string path1, string path2)
	{
		if (path2.index_of (Path.DIR_SEPARATOR_S)==0)
		{
			return path2;
		}
		else
		{
			 return Path.build_filename(path1,path2);
		}
	}
	
	public void build(string path)
	{
		//string curDir = runCommand("pwd");
		//string curDir = Environment.get_current_dir();
		//logMsg("Current directory %s",curDir);
		
		var directory = File.new_for_path (path);
		var enumerator = directory.enumerate_children (FileAttribute.STANDARD_NAME, 0);

		logMsg("Project directory %s",directory.get_path());

		List<FileInfo> vlpList = new List<FileInfo> ();

        FileInfo file_info;
        while ((file_info = enumerator.next_file ()) != null) 
        {
			//logMsg(file_info.get_file_type());
			//TODO: files doesn't seem to register here. Not sure why
			//if (file_info.get_file_type()==FileType.REGULAR)
			{
				string name = file_info.get_name();
				if (name!=null && name.length>4)
				{
					if (name.substring(-4,4)==".vlp")
					{
                        vlpList.append(file_info);
					}
				}
				
			}
        }
        
        if (vlpList.length ()>0)
        {
            vlpList.foreach ((entry) => {
                
                string vlpPath = combine(directory.get_path(),entry.get_name());
                string? targetGlib = null;
                string? projectName = null;
                string? projectType  = null;
                string? outputdirectory = null;
                string? buildscript = null;
                string? startupscript = null;
                logMsg("Found vlp file %s, processing it.",vlpPath);
                GLib.HashTable<string, string?> project = getAttributes(vlpPath,"/project/name","type");
                project.foreach ((key, val) =>
                {
                    projectName = key;
                    projectType = val;
                   
                });
                if (projectName==null)
                {
                    logMsg ("No project name defined");
                    return;
                }
                if (projectType==null)
                {
                    logMsg ("No project type defined");
                    return;
                }
                GLib.HashTable<string, string?> targets = getAttributes(vlpPath,"/project/targetglib",null);
                targets.foreach ((key, val) =>
                {
                    targetGlib = key;
                });
                
                GLib.HashTable<string, string?> buildscriptVal = getAttributes(vlpPath,"/project/buildscript",null);
                buildscriptVal.foreach ((key, val) =>
                {
                    buildscript = key;
                });
                
                GLib.HashTable<string, string?> startupscriptVal = getAttributes(vlpPath,"/project/startupscript",null);
                startupscriptVal.foreach ((key, val) =>
                {
                    startupscript = key;
                });
                
                GLib.HashTable<string, string?> outputdirectoryVal = getAttributes(vlpPath,"/project/copyoutput",null);
                outputdirectoryVal.foreach ((key, val) =>
                {
                    outputdirectory = key;
                });
                
                if (outputdirectory==null)
                {
                    outputdirectory = directory.get_path();
                }
                else
                {
                    outputdirectory = File.new_for_path (combine(directory.get_path(),outputdirectory)).get_path();
                }
                
                logMsg ("Project Name: %s",projectName);
                logMsg ("Project Type: %s",projectType);
                
                logMsg("-Package Dependencies");
                GLib.HashTable<string, string?> dependencies = getAttributes(vlpPath,"/project/dependencies/dependency","installed");
                dependencies.foreach ((key, val) =>
                {
                   logMsg ("%s => %s", key, val);
                });
                logMsg("-VAPI libraries");
                GLib.HashTable<string, string?> vapi = getAttributes(vlpPath,"/project/dependencies/vapiroot","installed");
                vapi.foreach ((key, val) =>
                {
                   logMsg ("%s => %s", key, val);
                });
                logMsg("-Source files");
                GLib.HashTable<string, string?> sources = new GLib.HashTable<string, string?> (str_hash, str_equal);
                GLib.HashTable<string, string?> sourceFiles = getAttributes(vlpPath,"/project/sources/file",null);
                
                sourceFiles.foreach ((key, val) =>
                {
                    if (key.contains("*"))
                    {
                        //set a file to understand the location of the pattern to check against
                        File file = File.new_for_path (combine(directory.get_path(),key.replace("*","a")));
                        File? dir = file.get_parent();
                        if (dir!=null)
                        {
                            //List the files and check for the pattern
                            FileEnumerator fileEnumerator = dir.enumerate_children (
                                "standard::*",
                                FileQueryInfoFlags.NOFOLLOW_SYMLINKS, 
                                null);
                            
                            string matchKey = key.replace(".","""\.""").replace("*",""".+""");
                            
                            Regex wordRegex = new Regex (matchKey, RegexCompileFlags.CASELESS, RegexMatchFlags.NOTEMPTY);

                            FileInfo info = null;
                            MatchInfo matchInfo;
                            while ((info = fileEnumerator.next_file (null)) != null) {
                                
                                wordRegex.match (info.get_name(), RegexMatchFlags.NOTEMPTY, out matchInfo);
                                if (matchInfo.get_match_count ()>0)
                                {
                                    logMsg ("%s => %s", info.get_name(), val);
                                    sources.set(info.get_name(),val);
                                }
                            }
                        }
                    }
                    else
                    {
                        sources.set(key,val);
                        logMsg ("%s => %s", key, val);
                        
                    }
                });
                string command = buildCommand(directory.get_path(),outputdirectory,projectName,projectType=="library",targetGlib,dependencies,vapi,sources);
                logMsg("Command: %s",command);
                
                if (buildscript!=null)
                {
                    string buildscriptpath = combine(directory.get_path(),buildscript);
                    saveBuildFile(buildscriptpath,command);
                }
                
                if (startupscript!=null && projectType=="application")
                {
                    string startupscriptpath = combine(directory.get_path(),startupscript);
                    saveStartupScript(startupscriptpath,directory.get_path(),projectName,vapi);
                }
                else if (startupscript!=null && projectType=="test")
                {
                    string startupscriptpath = combine(directory.get_path(),startupscript);
                    saveTestScript(startupscriptpath,directory.get_path(),projectName,vapi);
                }
                
                logMsg("Building");
                runCommand(command);
            });
		}
		else
		{
			logMsg("Cannot find any vlp file under %s",path);
		}
	}
	
	private void saveTestScript(string path,string rootPath, string projectName, GLib.HashTable<string, string?> vapi)
	{
		logMsg("Saving test script to %s",path);
		try 
		{
			var file = File.new_for_path (path);
			
			if (file.query_exists ()) 
			{
				file.delete ();
			}
			
			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
			
			dos.put_string ("#!/bin/sh\n");
            dos.put_string ("export LAUNCHDIR=$PWD\n"); 
            dos.put_string ("scriptdir=$(dirname ${0})\n");
            dos.put_string ("canondir=$(readlink -f $scriptdir)\n");
            dos.put_string ("cd $canondir\n");
           
			//dos.put_string ("cd  ");
			//dos.put_string (rootPath);
			//dos.put_string ("\n");
			
			vapi.foreach ((key, val) =>
			{
			   if (val!=null && val!="1")
			   {
				   dos.put_string ("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:");
				   dos.put_string (combine("$canondir",key));
				   dos.put_string ("\n");
			   }
			});
                        var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala"));
			dos.put_string(combine(valacDirectory.get_path(),"gtester/gtester --verbose $@ "));	
            		dos.put_string (combine("$canondir",projectName));
			//dos.put_string (combine(rootPath,projectName));
            FileUtils.chmod(path,0555);
		} 
		catch (GLib.Error e) 
		{
			logMsg("Error: %s", e.message);
		}
	}
	
	private void saveStartupScript(string path,string rootPath, string projectName, GLib.HashTable<string, string?> vapi)
	{
		logMsg("Saving startup script to %s",path);
		try 
		{
			var file = File.new_for_path (path);
			
			if (file.query_exists ()) 
			{
				file.delete ();
			}
			
			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
			
			dos.put_string ("#!/bin/sh\n");
            dos.put_string ("export LAUNCHDIR=$PWD\n");
            dos.put_string ("scriptdir=$(dirname ${0})\n");
            dos.put_string ("canondir=$(readlink -f $scriptdir)\n");
            dos.put_string ("cd $canondir\n");
            var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala"));
	    dos.put_string("export GIO_MODULE_DIR="+combine(valacDirectory.get_path(),"valac/giomodules\n")); 
	    dos.put_string("export GSETTINGS_SCHEMA_DIR="+combine(valacDirectory.get_path(),"valac/gschemas\n"));
            			
			//dos.put_string ("cd  ");
			//dos.put_string (rootPath);
			//dos.put_string ("\n");
			
			vapi.foreach ((key, val) =>
			{
			   if (val!=null && val!="1")
			   {
				   dos.put_string ("export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:");
				   dos.put_string (combine("$canondir",key));
				   dos.put_string ("\n");
			   }
			});
            dos.put_string (combine("$canondir",projectName));
			//dos.put_string (combine(rootPath,projectName));
			dos.put_string (" $@");
            FileUtils.chmod(path,0555);
		} 
		catch (GLib.Error e) 
		{
			logMsg("Error: %s", e.message);
		}
	}
	
	private void saveBuildFile(string path, string command)
	{
		logMsg("Saving build command to %s",path);
		try 
		{
			var file = File.new_for_path (path);
			
			if (file.query_exists ()) 
			{
				file.delete ();
			}

			var dos = new DataOutputStream (file.create (FileCreateFlags.REPLACE_DESTINATION));
			dos.put_string (command);
            FileUtils.chmod(path,0555);
		} 
		catch (GLib.Error e) 
		{
			logMsg("Error: %s", e.message);
		}
	}
    
    private string getLibName(string name)
    {
        if (name.length>3)
        {
            if (name.index_of("lib")==0)
            {
                return name.substring(3);
            }
        }
        return name;
    }
    
	
	private string buildCommand(string srcRoot,string outputpath,string projectName, bool isLibrary, 
		string? targetGlib,
		GLib.HashTable<string, string?> dependency, 
		GLib.HashTable<string, string?> vapi,
		GLib.HashTable<string, string?> source)
	{
		StringBuilder builder = new StringBuilder ();
		var valacDirectory = File.new_for_path(combine(GLib.Environment.get_home_dir(),"cadexis/vala")); 
		builder.append(combine(valacDirectory.get_path(),"valac/valac"));
		builder.append(" -X -lm");
		
		if (targetGlib!=null)
		{
			builder.append(" --target-glib ");
			builder.append(targetGlib);
		}
		
		dependency.foreach ((key, val) =>
		{
		   if (val==null || val!="2")
		   {
			   builder.append(" --pkg=");
			   builder.append(key);
		   }
		   if (val!=null && val!="1")
		   {
			   builder.append(" -X -l");
			   builder.append(getLibName(key));
		   }
		});
		
	 	builder.append(" -X -l");
		builder.append("gio-2.0");
		//builder.append(" -X -lposix"); 
	
		//This part is to integrate environment where vala is not installed using apt	
		builder.append(" --vapidir=");
		builder.append(combine(valacDirectory.get_path(),"valac/vapi"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include/glib-2.0"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include/gee-0.8"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include/libxml2"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include/json-glib-1.0"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include/libsoup-2.4"));
		builder.append(" -X -I");
		builder.append(combine(valacDirectory.get_path(),"valac/include"));
		builder.append(" -X -L");
		builder.append(combine(valacDirectory.get_path(),"lib"));

		GLib.Environment.set_variable("PKG_CONFIG_PATH",combine(valacDirectory.get_path(),"valac/pkgconfig"),true);
		GLib.Environment.set_variable("LD_LIBRARY_PATH",combine(valacDirectory.get_path(),"valac")+":"+combine(valacDirectory.get_path(),"lib"),true);
	
		vapi.foreach ((key, val) =>
		{
		   string path = combine(srcRoot,key);
		   builder.append(" --vapidir=");
		   builder.append(path);
		   if (val!=null && val!="1")
		   {
			   builder.append(" -X -I");
			   builder.append(path);
			   builder.append(" -X -L");
			   builder.append(path);
		   }
		});
		
		if (isLibrary)
		{
			builder.append(" --library=");
			builder.append(projectName);
			builder.append(" --vapi=");
			builder.append(combine(outputpath,projectName));
			builder.append(".vapi -H ");
			builder.append(combine(outputpath,projectName));
			builder.append(".h -X -fPIC -X -shared -o ");
			builder.append(combine(outputpath,projectName));
			builder.append(".so ");
		}
		else
		{
			builder.append(" -o ");
			builder.append(combine(outputpath,projectName));
		}
		
		source.foreach ((key, val) =>
		{
		    builder.append(" ");
		    builder.append(combine(srcRoot,key));
		});
		
		return (owned) builder.str;
	}
	
	private string runCommand(string cmd)
	{
		string execute = cmd;
		string output = "";
		string err = "";
		int exitcode = -1;
		bool result= false;

		try 
		{
			result= GLib.Process.spawn_command_line_sync(execute, out output, out err, out exitcode);
		} 
		catch (SpawnError e) 
		{
			logMsg("spawn error!\n"+e.message);
		}

		logMsg("Output: %s\nError: %s\nExitcode: %s\nResult: %s\n", output,err,exitcode.to_string(), result.to_string());
		
		return output;
	}
}

public static GLib.HashTable<string, string?> getAttributes(string filePath, string xpath, string? attrName)
{
	GLib.HashTable<string, string?> retHashtable = new GLib.HashTable<string, string?> (str_hash, str_equal);
	
	//https://wiki.gnome.org/Projects/Vala/XmlSample
	
	Xml.Doc* doc = Parser.parse_file (filePath);
	if(doc==null) logMsg("failed to read the .xml file");

	Context ctx = new Context(doc);
	if(ctx==null) logMsg("failed to create the xpath context");

	Xml.XPath.Object* obj = ctx.eval_expression(xpath);
	if(obj==null)
	{
		logMsg("failed to evaluate xpath");
	}

	Xml.Node* node = null;
	
	if ( obj->nodesetval != null)
	{
		int numControls = obj->nodesetval->length();
		for (int i=0;i<numControls;i++)
		{	
			node = obj->nodesetval->item(i);
			string nodeVal = node->get_content();
			string attrVal = null;
			if (attrName!=null)
			{			
				Xml.Attr* attr = null;
				attr = node->properties;
				while ( attr != null )
				{
					if (attr->name == attrName)
					{
						attrVal = attr->children->content;
					}
					attr = attr->next;
				}
			}
			retHashtable.insert (nodeVal, attrVal);
		}
	} 
	else 
	{
			logMsg("failed to find the expected node");
	}
	
	
	delete obj;
	delete doc;
	
	return retHashtable;
}

public static void logMsg(string msg,...)
{
	var va_list = va_list ();
	StringBuilder builder = new StringBuilder ();
	builder.append_vprintf (msg+"\n", va_list);
	stderr.printf((owned) builder.str);
}

ValaBuild man = null;

int main (string[] args) 
{    
	if (args==null || args.length<2)
	{
		logMsg("valabuild - version %s".printf(ValaBuild.version));
		logMsg("Copyright (C) %s".printf(ValaBuild.copyright));
		logMsg("Tool to facilitate vala building.");
		logMsg("\nusage: valabuild directory_path");
		return 1;
	}
	try 
	{
        string path = args[1];
		logMsg("Building %s",path);
		man = new ValaBuild();
		man.build(path);
		return 0;
    } 
    catch (GLib.Error e) 
    {
        stderr.printf ("Error: %s\n", e.message);
        return 1;
    }
}