/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2014. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */

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

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.websphere.commerce.WebSphereCommerceHelper
import com.urbancode.commons.util.properties.LayoutPreservingProperties

final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def isWindows = apTool.isWindows
final def workDir = new File('.').canonicalFile
final def props = apTool.getStepProperties();
def exitVal = 0;

def targetEnv = props['targetEnv']
def propFile = props['propFile']
def privatePropFile = props['privatePropFile']
def settings = props['settings']
def privateSettings = props['privateSettings']
def antHome = props['antHome']
def wasHome = props['wasHome']

def processEnvFile = { inFile, outFile ->
    println "Modifying and saving file " + inFile.toString() + " as " + outFile.toString()
    String currLine = "";
    ArrayList<String> gatheredLines = new ArrayList<String>();

    BufferedReader reader = new BufferedReader(new FileReader(inFile));
    while ((currLine = reader.readLine()) != null) {
        gatheredLines.add(currLine);
    }
    reader.close();

    BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
    Pattern pattern = Pattern.compile("\\s*set|export\\s*(ANT_HOME|WAS_HOME)\\s*=\\s*(.*)");
    for (String line : gatheredLines) {
        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            String propValue = ""
            if (matcher.group(1).equals("WAS_HOME")) {
                if (!(wasHome =~ /^\$\{/)) propValue = wasHome
            } else if (matcher.group(1).equals("ANT_HOME")) {
                if (!(antHome =~ /^\$\{/)) propValue = antHome
            }
            if (! WebSphereCommerceHelper.isEmpty(propValue)) {
                line = WebSphereCommerceHelper.isEmpty(matcher.group(2)) ? line + propValue : line.replace(matcher.group(2), propValue)
                println "Modified: " + line
            }
        }
        writer.writeLine(line);
    }
    writer.close();
}

def propHandler = { propFileName, userSettings ->
    LayoutPreservingProperties p = new LayoutPreservingProperties();
    FileInputStream fis;
    try {
        fis = new FileInputStream(propFileName)
        p.load(fis);
    } catch (Exception e) {
        throw new RuntimeException();
    } finally {
        fis.close();
    }
    p.setRemoveComments(false);

    userSettings.split("(?<=(^|[^\\\\])(\\\\{2}){0,8}),").each { prop ->
        def parts = prop.split("(?<=(^|[^\\\\])(\\\\{2}){0,8})=",2);
        def keyName = parts[0];
        def keyValue = parts.size() == 2 ? parts[1] : "";
        keyName = keyName.replace("\\=", "=").replace("\\,", ",").replace("\\\\", "\\").replace("\\", "")
        keyValue = keyValue.replace("\\=", "=").replace("\\,", ",").replace("\\\\", "\\").replace("\\", "")
        p.put(keyName, keyValue)
    }

    p.saveAs(new File(propFileName));
}

try {
    if (WebSphereCommerceHelper.isEmpty(propFile)) propFile = "deploy-" + targetEnv + ".properties"
    if (WebSphereCommerceHelper.isEmpty(privatePropFile)) privatePropFile = "deploy-" + targetEnv + ".private.properties"

    propFile = new File(WebSphereCommerceHelper.findFile(".", propFile)).getCanonicalPath()
    privatePropFile = new File(WebSphereCommerceHelper.findFile(".", privatePropFile)).getCanonicalPath()
    propHandler(propFile, settings)
    propHandler(privatePropFile, privateSettings)

    File inEnvFile, outEnvFile;
    String envFileName = isWindows ? "setenv.bat" : "setenv"
    String templateFileName = isWindows ? "wcbd-setenv.bat.template" : "wcbd-setenv.template"

    String envFilePath = WebSphereCommerceHelper.findFile(workDir.getCanonicalPath(), envFileName)
    if (WebSphereCommerceHelper.isEmpty(envFilePath)) {
        inEnvFile = new File(WebSphereCommerceHelper.findFile(workDir.getCanonicalPath(), templateFileName))
        outEnvFile = new File(inEnvFile.getParent() + File.separator + envFileName)
    } else {
        outEnvFile = new File(envFilePath).getCanonicalFile()
        inEnvFile = outEnvFile
    }

    processEnvFile(inEnvFile, outEnvFile)
}
catch (Exception e) {
    e.printStackTrace();
    exitVal=1;
}
System.exit(exitVal);
