/*
* 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
*/

package com.urbancode.air.plugin.iisconfiguration.helper

class AppCmdCLIHelper {
    def appCmdPath

    //static variables which represent AppCmd object types
    static String SITES = "site"
    static String APPLICATIONS = "app"
    static String APPLICATION_POOLS = "apppool"

    //constructor
    public AppCmdCLIHelper(def appCmdPath = "C:\\Windows\\System32\\inetsrv\\appcmd.exe"){
        this.appCmdPath = appCmdPath
    }

    //AppCmd.exe list <objectType> then format result into a Map of: [name:[propName:propValue]]
    public Map listObjects(def objectType) {
        Map result
        //load process
        def appCmdArgs = [appCmdPath, "list", objectType]
        println("Command: ${appCmdArgs.join(" ")}")
        def appCmdProcess = appCmdArgs.join(" ").execute()
        appCmdProcess.out.close()

        //capture output
        def oStream = new ByteArrayOutputStream()
        appCmdProcess.waitForProcessOutput(oStream, System.err)
        def outputString = oStream.toString()

        println(outputString)
        result = stringToMap(outputString)
        return result
    }

    //format raw output from AppCmd into a map for objectType
    private Map stringToMap(String appCmdOutputString){
        Map result = [:]
        def name, propSplit, propMap, propData, keyVal

        //capture (objectType) ("objectNameInQuotes") (listOfPropertyKeyValuePairs)
        def regexParseMatcher = ( appCmdOutputString =~ /(.*) (".*") \((.*)\)/ )
        regexParseMatcher.each{
            propMap = [:]
            name = it[2].replace("\"", "")

            it[3].split(",").each{
                keyVal = it.split(":")
                if (keyVal.size() > 1){
                    //in case there are other ":" in the value, join them back together
                    propMap[keyVal[0]] = keyVal[1..-1].join(":")
                }
            }
            result[name] = propMap
        }
        return result
    }
}
