package me.automationdomination.plugins.threadfix.service;

import hudson.EnvVars;
import java.io.PrintStream;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WindowsEnvironmentVariableParsingService implements EnvironmentVariableParsingService {

	private final Pattern environmentVariablePattern = Pattern.compile("%.+?%");

	@Override
	public String parseEnvironentVariables(final EnvVars envVars, final String value, PrintStream log) {
		final Matcher matcher = this.environmentVariablePattern.matcher(value);

		String parsedValue = value;

		while (matcher.find()) {
			final String matchedValue = matcher.group();
			log.println("matchedValue: " + matchedValue);

			// TODO: can this be done more efficiently?
			final String environmentVariableKey = matchedValue.replaceAll("%", "");
			//
			log.println("environmentVariableKey: " + environmentVariableKey);

			String environmentVariableValue = envVars.get(environmentVariableKey);
			//
			log.println("environmentVariableValue: " + environmentVariableValue);

			// if this is null, that means the environment variable was not found
			if (environmentVariableValue != null) {

				environmentVariableValue.replaceAll("\\\\", "\\\\\\\\");

				// TODO: can this be done more efficiently?
				parsedValue = parsedValue.replaceAll("%" + environmentVariableKey + "%", environmentVariableValue);
				//
				log.println("parsedValue: " + parsedValue);
			}
		}

		return parsedValue;
	}

}

@@ -1163,21 +1163,47 @@
 null) %7B%0A
-%0A
 %09%09%09%09
+environmentVariableValue = 
 environm
@@ -1252,16 +1252,79 @@
 %5C%5C%5C%22);%0A%0A
+%09%09%09%09log.println(%22this better work again with the slashes!!!%22);%0A
 %09%09%09%09// T

fix bug replacing whacks on windows environment variable parsing