package hudson.plugins.ws_cleanup;

import hudson.AbortException;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.tasks.BuildWrapper;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.kohsuke.stapler.DataBoundConstructor;
/**
 * 
 * @author vjuranek
 *
 */
public class PreBuildCleanup extends BuildWrapper {

	private static final Logger LOGGER = Logger.getLogger(PreBuildCleanup.class.getName());

	private final List<Pattern> patterns;
	private final boolean deleteDirs;
	private final String cleanupParameter;
        private final String externalDelete;

	@DataBoundConstructor
	public PreBuildCleanup(List<Pattern> patterns, boolean deleteDirs, String cleanupParameter, String externalDelete) {
		this.patterns = patterns;
		this.deleteDirs = deleteDirs;
		this.cleanupParameter = cleanupParameter;
                this.externalDelete = externalDelete;
	}

	public List<Pattern> getPatterns(){
		return patterns;
	}
	
	public boolean getDeleteDirs(){
		return deleteDirs;
	}

	public String getCleanupParameter() {
		return this.cleanupParameter;
	}
	
        public String getExternalDelete() {
            return this.externalDelete;
        }
        
	@Override
	public DescriptorImpl getDescriptor() {
		return (DescriptorImpl) super.getDescriptor();
	}

	
	@Override
	public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
		return new NoopEnv();
	}

	@Override
	public void preCheckout(AbstractBuild build, Launcher launcher,
			BuildListener listener) throws AbortException {

		// Check if a cleanupParameter has been setup and skip cleaning workspace if set to false
		if (cleanupParameter != null && !cleanupParameter.isEmpty()) {
			Boolean doCleanup = new Boolean((String)build.getBuildVariables().get(this.cleanupParameter));
			if (!doCleanup) {
				listener.getLogger().append("\nSkip deletion of workspace, because cleanup parameter was set to false\n");
				return;
			}
		}

		listener.getLogger().append("\nDeleting project workspace... ");
		FilePath ws = build.getWorkspace();
               
		if (ws != null) {
		    RemoteCleaner cleaner = RemoteCleaner.get(patterns, deleteDirs, externalDelete, listener, build);
			try {
				// Retry the operation a couple of times,
				int retry = 3;
				while (true) {
					try {
						if (!ws.exists())
							return;

						cleaner.perform(ws);
						listener.getLogger().append("done\n\n");
						break;
					} catch (IOException e) {
						retry -= 1;
						if (retry > 0) {
							// Swallow the I/O exception and retry in a few seconds.
							Thread.sleep(3000);
						} else {
							listener.getLogger().append("Cannot delete workspace: " + e.getMessage() + "\n");
							LOGGER.log(Level.SEVERE, "Cannot delete workspace", e);

							throw new AbortException("Cannot delete workspace: " + e.getMessage());
						}
					}
				}
			} catch(InterruptedException e) {
				LOGGER.log(Level.SEVERE, "Cleanup interrupted", e);
			}
		}
	}

	@Extension(ordinal=9999)
	public static final class DescriptorImpl extends Descriptor<BuildWrapper> {

		@Override
		public String getDisplayName() {
			return Messages.PreBuildCleanup_Delete_workspace();
		}

	}

	class NoopEnv extends Environment{
	}
}

@@ -2086,90 +2086,80 @@
 r().
-append(%22%5CnSkip deletion of workspace, because cleanup parameter was set to false%5Cn
+println(%22%5BWS-CLEANUP%5D Clean-up disabled, skipping deletion of workspace.
 %22);%0A
@@ -2207,18 +2207,30 @@
 r().
-append(%22%5Cn
+println(%22%5BWS-CLEANUP%5D 
 Dele
@@ -2254,17 +2254,16 @@
 space...
- 
 %22);%0A%09%09Fi
@@ -2563,16 +2563,18 @@
 xists())
+ %7B
 %0A%09%09%09%09%09%09%09
@@ -2580,16 +2580,24 @@
 %09return;
+%0A%09%09%09%09%09%09%7D
 %0A%0A%09%09%09%09%09%09
@@ -2656,16 +2656,15 @@
 nd(%22
-d
+ D
 one%5Cn
-%5Cn
 %22);%0A
@@ -2870,36 +2870,36 @@
 istener.
-getLogger().append(%22
+error(%22%5BWS-CLEANUP%5D 
 Cannot d
@@ -2937,15 +2937,8 @@
 ge()
- + %22%5Cn%22
 );%0A%09
@@ -2999,17 +2999,16 @@
 e%22, e);%0A
-%0A
 %09%09%09%09%09%09%09t

Normalise console logging