
/**
 * JMichelle (Java Midori Shell)
 * Copyright (C) 2000 Midori IGA 
 *   (http://www01.u-page.so-net.ne.jp/db3/midori/midosoft.html)
 * 
 * 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 2 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package jp.ne.nifty.iga.midori.shell.io;

import jp.ne.nifty.iga.midori.shell.eng.MdShellEnv;
import jp.ne.nifty.iga.midori.shell.dir.*;
import java.io.*;
import java.util.*;
import java.text.Collator;
import java.text.CollationKey;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;

/**
 * JMichelle (Java Midori Shell) : utility.
 */
public class MdShellUtilExec
	extends Thread
{
	/**
	 * A synchronous process start.
	 */
	public static int exec(MdShellEnv shellenv,String strCommand)
	{
		if(strCommand==null
		|| strCommand.trim().length()==0)
		{
			return -1;
		}

		if(strCommand.indexOf('&')<0)
		{
			return internalExec(shellenv,strCommand,shellenv.getIn());
		}
		else
		{
			// It gets rid of &.
			StringTokenizer toknizerTab=new StringTokenizer(strCommand,"&",false);
			strCommand=toknizerTab.nextToken();
			execAsync(shellenv,strCommand);
			return 0;
		}
	}

	/**
	 * Non-synchronous process start.
	 */
	private static void execAsync(MdShellEnv shellenv,String strCommand)
	{
		if(strCommand==null
		|| strCommand.trim().length()==0)
		{
			return;
		}

		MdShellUtilExec shellutil=new MdShellUtilExec(shellenv,strCommand);
		shellutil.start();
		try{
			Thread.sleep(1000);
		}catch(InterruptedException ex){
			System.out.println(ex.toString());
		}
	}

	private static int internalExec(MdShellEnv shellenv,String strCommand,InputStream inStream)
	{
		Calendar calStart=Calendar.getInstance();
		SimpleDateFormat sdFormat=new SimpleDateFormat("HH:mm:ss");
		{
			StringBuffer strbufWrk=new StringBuffer();
			strbufWrk.append(sdFormat.format(calStart.getTime())+" ");
			if(inStream!=null)
			{
				strbufWrk.append("An executive start.");
			}
			else
			{
				strbufWrk.append("back ground executive start.");
			}
			strbufWrk.append(" ["+strCommand+"]");
			System.out.println(strbufWrk.toString());
		}

		// tokenize.
		Vector vecList=new Vector();
		StringTokenizer toknizerTab=new StringTokenizer(strCommand," \t\n",false);
		for(;toknizerTab.hasMoreTokens();)
		{
			String strToken=toknizerTab.nextToken();
			if(strToken==null)break;
			vecList.addElement(strToken);
		}
		String[] straryCommands=new String[vecList.size()];
		for(int index=0;index<vecList.size();index++)
		{
			straryCommands[index]=(String)vecList.elementAt(index);

			if(index==0
			&& shellenv.getCurrentDirectory() instanceof MdShellDirDirectoryFileSystem)
			{
				// fullfill directory if load module is exists.
				MdShellDirDirectoryFileSystem filesystem=(MdShellDirDirectoryFileSystem)shellenv.getCurrentDirectory();
				String strSeparator=System.getProperty("file.separator");
				File fileExistCheck=new File(MdShellDirFactory.uri2native(filesystem.getName())+strSeparator+straryCommands[index]);
				if(fileExistCheck.exists())
				{
					straryCommands[index]=MdShellDirFactory.uri2native(filesystem.getName())+strSeparator+straryCommands[index];
				}
			}

		}

		Process proc=null;
		try{
			File fileWrkDirectory=null;
			if(shellenv.getCurrentDirectory() instanceof MdShellDirDirectoryFileSystem)
			{
				MdShellDirDirectoryFileSystem filesystem=(MdShellDirDirectoryFileSystem)shellenv.getCurrentDirectory();
				fileWrkDirectory=new File(MdShellDirFactory.uri2native(filesystem.getName()));
			}
			proc=Runtime.getRuntime().exec(straryCommands,null,fileWrkDirectory);
		}catch(IOException ex){
			System.out.println("fail to invoke command ["+strCommand+"]: "+ex.toString());
			return -1;
		}

		MdShellStreamConnectThread threadStdin=null;

		// Redirect input only when synchronism is carried out.
		if(inStream!=null)
		{
			threadStdin=new MdShellStreamConnectThread(inStream,proc.getOutputStream());
			threadStdin.start();
		}

		MdShellStreamConnectThread threadStdout=new MdShellStreamConnectThread(proc.getInputStream(),System.out);
		MdShellStreamConnectThread threadStderr=new MdShellStreamConnectThread(proc.getErrorStream(),System.out);

		threadStdout.start();
		threadStderr.start();

		try{
			// Thread It joins the completion.
			threadStdout.join();
		}catch(InterruptedException ex){
			System.out.println(ex.toString());
		}

		int i_status=proc.exitValue();

		if(threadStdin!=null)
		{
			threadStdin.close();
		}

		threadStdout.close();
		threadStderr.close();

		try{
			proc.getOutputStream().close();
		}catch(IOException ex){
			System.out.println(ex.toString());
			ex.printStackTrace();
		}

		Calendar calEnd=Calendar.getInstance();
		String strMillisec=NumberFormat.getNumberInstance().format((double)(calEnd.getTime().getTime()-calStart.getTime().getTime())/1000)+"sec";

		System.out.println();

		{
			StringBuffer strbufWrk=new StringBuffer();
			strbufWrk.append(sdFormat.format(calEnd.getTime())+" ");
			if(inStream!=null)
			{
				strbufWrk.append("Executive completion.");
			}
			else
			{
				strbufWrk.append("back ground executive completion.");
			}
			strbufWrk.append(" "+strMillisec+" return value="+i_status);
			System.out.println(strbufWrk.toString());
		}

		return i_status;
	}

	private MdShellEnv shellenv=null;
	private String strCommand=null;
	public MdShellUtilExec(MdShellEnv shellenv,String strCommand)
	{
		this.shellenv=shellenv;
		this.strCommand=strCommand;
	}

	public void run()
	{
		internalExec(shellenv,strCommand,null);
	}
}

