/*
 * Created on 2004-08-17
 *
 * Part of the Symbian development plug-in for Eclipse
 * Copyright (C) Mikołaj Zalewski, 2004
 */
package pl.zalewski.mikolaj.symbdev;

import java.io.File;
import java.io.IOException;

import org.eclipse.cdt.core.CommandLauncher;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;

/**
 * @author mikolaj
 *
 * Launches a Symbian command is the correct environment and in the correct directory
 */
public class SymbianCommandLauncher extends CommandLauncher {

    /**
     * Default constructor
     */
    public SymbianCommandLauncher() {
        super();
    }

    public Process execute(IProject prj, String cmd, String[] args) throws CoreException
    {
        return execute(prj, cmd, args, false);
    }
    
    /**
     * Sets if the process should start in the directory with bld.inf as configured
     * in the project properties. By default it is <code>true</code>.
     * @param useGroupPath <code>true</code> if the process should start in the
     * directory with bld.inf as configured in the project properties.
     */
    public void setUseGroupPath(boolean useGroupPath)
    {
        fUseGroupPath=useGroupPath;
    }
    
    /**
     * Executes a command with the correct environment and working directory
     * @param cmd
     * @return
     */
    public Process execute(IProject prj, String cmd, String[] args, boolean useInternalShell) throws CoreException
    {
	    String workDir;
	    if (fUseGroupPath) workDir=SymbianCommandHelper.getWorkingDirectory(prj);
	    	else workDir=null;
        String[] envTab=SymbianCommandHelper.buildEnvironment(prj, !useInternalShell);
        
        //a lot of build commands are *.bat files, so start through the command shell
        fCommandArgs=new String[args.length+3];
        System.arraycopy(args, 0, fCommandArgs, 3, args.length);
        fCommandArgs[0]=SymbianCommandHelper.getOSShell(!useInternalShell);
        fCommandArgs[1]="/c";
        fCommandArgs[2]=cmd;
        
        // there is a bug in the Win32 version of CommandLauncher - the
        // environment is not set, so we start the process manually
        setErrorMessage("");
        try {
            fProcess=Runtime.getRuntime().exec(fCommandArgs, envTab, (workDir!=null?new File(workDir):null));
        }
        catch (IOException e)
        {
            setErrorMessage(e.getMessage());
            return null;
        }
        return fProcess;
    }
    
    boolean fUseGroupPath=true;
}
