package com.cloudbees.genapp.metadata;

 /*
 * Copyright 2010-2013, CloudBees Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

/**
 * This class writes environment variables from a given Metadata instance to a file in $control_dir.
 * It can write those either in java properties or bash format.
 *
 * Typical use, if the metadata is given:
 *
 * boolean safe = true;
 * boolean includeDeprecatedEntries = false;
 * (new EnvBuilder(safe, includeDeprecatedEntries, metadata)).writeControlFile("env_safe");
 */

public class EnvBuilder {

    private boolean safe;
    private boolean includeDeprecatedEntries;
    private Metadata metadata;
    private static final List<Pattern> deprecatedKeys = Arrays.asList(Pattern.compile("^MYSQL_.*$"));

    /**
     * The default constructor.
     * @param safe If false, the environment variables will be written with the java properties format.
     *             If true, it will be written with the bash format.
     * @param includeDeprecatedEntries If true, includeDeprecatedEntries environment variables will not be written.
     * @param metadata The metadata that contains the environment variables to be parsed.
     */

    public EnvBuilder(boolean safe, boolean includeDeprecatedEntries, Metadata metadata) {
        this.safe = safe;
        this.includeDeprecatedEntries = includeDeprecatedEntries;
        this.metadata = metadata;
    }

    /**
     * Generates a list of key-value Strings from the environment variables contained in the metadata.
     * @return A list of formatted environmental key-value pairs.
     */
    private List<String> getProperties() {
        List<String> properties = new ArrayList<String>();
        for (Map.Entry<String, String> field: metadata.getEnvironment().entrySet()) {
            String fieldKey = field.getKey();
            String fieldValue = field.getValue();
            if (includeDeprecatedEntries || !isDeprecated(fieldKey)) {
                properties.add(formatProperty(fieldKey, fieldValue));
            }
        }
        return properties;
    }

    protected boolean isDeprecated(String fieldKey) {
        boolean isDeprecated = false;
        for (Pattern deprecatedKey : deprecatedKeys) {
            if (deprecatedKey.matcher(fieldKey).find()) {
                isDeprecated = true;
                break;
            }
        }
        return isDeprecated;
    }

    /**
     * Formats a raw key-value pair to either java properties format (if initialized with safe = false)
     * or bash format (if initialized with safe = true), in which case it will replace invalid characters with
     * an underscore character.
     * @param fieldKey The key of the key-value pair to format.
     * @param fieldValue The value of the key-value pair to format.
     * @return
     */

    private String formatProperty(String fieldKey, String fieldValue) {
        if (!safe) {
            // Remove whitespace from name and quotes the value.
            // This typically still returns bash-unsafe key-value pairs.
            return fieldKey + "=" + fieldValue;
        } else {
            // This returns bash-safe variables.
            // First, we remove any illegal characters
            fieldKey = fieldKey.replaceAll("[^a-zA-Z0-9_]+", "_");
            // In case the variable name is starting with a digit, we add in an underscore instead.
            if (fieldKey.matches("^[0-9].*$")) {
                fieldKey = "_" + fieldKey;
            }
            // All return characters should be escaped for bash
            fieldValue = fieldValue.replaceAll("\\n", "\\ \n");
            return fieldKey + "='" + fieldValue + "'";
        }
    }

    /**
     * Write the environment variables generated by this EnvBuilder instance to a file.
     * @param controlPath Path to the env file to be written, relative to the control_dir environment variable.
     * @throws IOException
     */

    public void writeControlFile(String controlPath) throws IOException {
        Map<String, String> env = System.getenv();
        String controlAbsolutePath = env.get("control_dir") + controlPath;
        File controlFile = new File(controlAbsolutePath);

        if (!controlFile.exists())
            controlFile.createNewFile();

        List<String> envProperties = getProperties();
        PrintWriter bufferedWriter = new PrintWriter(new BufferedWriter(new FileWriter(controlFile)));
        for (String line : envProperties) {
            bufferedWriter.println(line);
        }
        bufferedWriter.close();
    }
}

@@ -4632,30 +4632,28 @@
         
-String
+File
  control
 Absolute
@@ -4648,23 +4648,24 @@
 trol
-AbsolutePath = 
+File = new File(
 env.
@@ -4686,83 +4686,25 @@
 ir%22)
- + controlPath;%0A        File controlFile = new File(controlAbsolute
+, control
 Path);%0A%0A
     
@@ -4695,24 +4695,25 @@
 trolPath);%0A%0A
+%0A
         if (

split parent folder and child file