/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2002-2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper
import com.urbancode.air.plugin.iisconfiguration.Util
import com.urbancode.air.plugin.iisconfiguration.Globals
import groovy.util.AntBuilder
import groovy.io.FileType

//initialize plugin tools
def s = File.separator
def apTool = new AirPluginTool(args[0], args[1])
def isWindows = apTool.isWindows
def props = apTool.getStepProperties()
def commandHelper = new CommandHelper(new File(".").canonicalFile)
def antBuilder = new AntBuilder()
def archiveXML = Util.findFileRecursivelyByName(Globals.CONFIG_FILE)

//initialize ucd related variables
def ucdUsername = apTool.getAuthTokenUsername()
def ucdPassword = apTool.getAuthToken()
def ucdUri = new URI(System.getenv("AH_WEB_URL"))
//map [<property to tokenize>:@<token>@, <another property>:@<another token>@]
def propertiesToTokenizeString = props['propertiesToTokenize']
def propertiesToTokenizeMap = [:]
def tokenDelimiter = props['tokenDelimiter']

def main = {
    //format propertiesToTokenize to be a map for easier accesss
    propertiesToTokenizeString.split("\n").each{
        def keyValuePair = it.split("=")
        propertiesToTokenizeMap[keyValuePair[0]] = keyValuePair[1]
    }

    //string "buffer" (yes strings are immutable) for changes
    def fileChanges = archiveXML.text

    //replace property values with tokens inside of the archive.xml file
    propertiesToTokenizeMap.each { property, token ->
        if (fileChanges.contains(property)) {
            def propertiesToBeChanged = fileChanges =~ / ${property}=(".*?")/
            println("The following token replacements will occur:")
            propertiesToBeChanged.each{group ->
                println("${property} value ${group[1]} replaced with \"${tokenDelimiter}${token}${tokenDelimiter}\"")
            }
            fileChanges = fileChanges.replaceAll(~/ ${property}=".*?"/, " ${property}=\"${tokenDelimiter}${token}${tokenDelimiter}\"")
        }
    }
    println("\nReplacements complete.")
    println("Writing changes to configuration file ${Globals.CONFIG_FILE}...")
    //write to file once
    archiveXML.text = fileChanges
    println("Changes written to file.")
}

//go
main()
