package jenkins.plugins.clangscanbuild.commands;

import hudson.FilePath;
import hudson.Launcher;
import hudson.Launcher.ProcStarter;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.util.ArgumentListBuilder;

import java.io.IOException;

@SuppressWarnings("rawtypes")
public class BuildContextImpl implements BuildContext{

	private AbstractBuild build;
	private Launcher launcher;
	private BuildListener listener;

	public BuildContextImpl( AbstractBuild build, Launcher launcher, BuildListener listener ){
		super();
		this.build = build;
		this.launcher = launcher;
		this.listener = listener;
	}

	public FilePath getWorkspace() {
		return build.getWorkspace();
	}

	public int waitForProcess( ProcStarter processStarter ){
		try {
			return processStarter.join();
		} catch (IOException e) {
			log( "Error starting process: " + processStarter + "\n" + e.getMessage() );
		} catch (InterruptedException e) {
			log( "Process was interrupted: " + processStarter + "\n" + e.getMessage() );
		}
		return 1;
	}

	public void log( String message ){
		listener.getLogger().println( message );
	}

	@Override
	public FilePath getBuildFolder() {
		return new FilePath( build.getRootDir() );
	}

	@Override
	public int waitForProcess( FilePath presentWorkingDirectory, ArgumentListBuilder command ){
		ProcStarter procStarter = launcher.launch();
		procStarter.pwd( presentWorkingDirectory );
		procStarter.stdout( listener ); // maps output from command to console output.  Some commands will need to override this because they need to capture the output.
		procStarter.cmds( command );
		
		log( "EXECUTING COMMAND:" + procStarter.cmds() );

		try {
			return procStarter.join();
		} catch (IOException e) {
			log( "Error starting process: " + procStarter + "\n" + e.getMessage() );
		} catch (InterruptedException e) {
			log( "Process was interrupted: " + procStarter + "\n" + e.getMessage() );
		}
		
		return 1; // ERROR
	}

}

@@ -43,16 +43,39 @@
 mands;%0A%0A
+import hudson.EnvVars;%0A
 import h
@@ -259,16 +259,50 @@
 Builder;
+%0Aimport hudson.model.TaskListener;
 %0A%0Aimport
@@ -1382,16 +1382,17 @@
 mand )%7B%0A
+%0A
 %09%09ProcSt
@@ -1430,16 +1430,383 @@
 unch();%0A
+        try %7B%0A            final EnvVars buildEnvironment = build.getEnvironment( TaskListener.NULL );%0A            procStarter.envs( buildEnvironment );%0A        %7D catch (IOException e) %7B%0A%09%09%09log( %22Error getting environment: %22 + e.getMessage() );%0A        %7D catch (InterruptedException e) %7B%0A%09%09%09log( %22Interrupted when getting environment: %22 + e.getMessage() );%0A        %7D%0A%0A
 %09%09procSt

Make sure to pass environment to scan-build