/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

def propFileName = props['propFile']
def dirOffset = props['dir']?:'.'
workDir = new File(workDir, dirOffset).canonicalPath
def includes = props['includes']
def excludes = props['excludes']
def startDelimiter = props['startDelimiter']?:''
def endDelimiter = props['endDelimiter']?:''
def propertyPrefix = props['propertyPrefix']
def envPropValues = props['envPropValues']
def explicitTokens = props['explicitTokens']
def propFile = new File(workDir, propFileName)
def propFileExistst = false

try {

    def Properties properties = new Properties()
    if (propFile.exists()) {
        propFileExistst = true
        println "Found existing input property file: ${propFile.canonicalPath}"
        def tempProps = new Properties()
        propFile.withInputStream { stream ->
            tempProps.load(stream)
        }
        tempProps.each { k,v ->
            properties.setProperty(startDelimiter + k + endDelimiter, v)

        }
    }
    if(envPropValues) {
       if (propertyPrefix) {
            println "Looking for properties starting with $propertyPrefix"
        }
        //this is jeffs magic regex to split on ,'s preceded by even # of \ including 0
        envPropValues.split("(?<=(^|[^\\\\])(\\\\{2}){0,8}),").each { prop ->
            //split out the name
            def parts = prop.split("(?<=(^|[^\\\\])(\\\\{2}){0,8})=",2);
            def propName = parts[0];
            def propValue = parts.size() == 2 ? parts[1] : "";
            //replace \, with just , and then \\ with \
            propName = propName.replace("\\=", "=").replace("\\,", ",").replace("\\\\", "\\")
            propValue = propValue.replace("\\=", "=").replace("\\,", ",").replace("\\\\", "\\")

            if ((!propertyPrefix || propName.startsWith(propertyPrefix))) {
                properties.setProperty(startDelimiter + propName + endDelimiter, propValue)
//                println 'added: ' + startDelimiter + propName + endDelimiter + ':' + propValue
            }
        }
    }

    if (explicitTokens) {
        explicitTokens.eachLine {
            if (it && it.indexOf('->') > 0) {
                def index = it.indexOf('->')
                def propName = it.substring(0, index).trim()
                def propValue = index < (it.length() - 2) ? it.substring(index + 2) : ""
                properties.setProperty(propName, propValue)
//                println 'added: ' + propName + ':' + propValue
            }
            else if (it) {
                println "Found invalid explicit token $it - missing -> separator"
            }
        }
    }
    propFile.withOutputStream { outStream ->
        properties.store(outStream, 'Auto generated property file')
    }

    properties.each { k,v ->
        println "added: $k:$v"
    }

    def ant = new AntBuilder()
    if (properties.size() > 0) {
        if (excludes) {
            ant.replace(
                    dir:dirOffset,
                    summary: 'true',
                    replacefilterfile: propFile.canonicalPath,
                    includes: includes,
                    excludes: excludes,
                    defaultexcludes: 'no')

        }
        else {
            ant.replace(
                    dir:dirOffset,
                    summary: 'true',
                    replacefilterfile: propFile.canonicalPath,
                    includes: includes,
                    defaultexcludes: 'no')
        }
    }
    else {
        println 'Did not find any properties or explicit tokens for replacement.'
    }
}
catch (Exception e) {
    e.printStackTrace()
    println "Error replacing tokens!"
    System.exit(1)
}
finally {
    if (propFile != null && !propFileExistst) {
        propFile.delete()
    }
}

System.exit(0)

