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

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()
        def eStream = new ByteArrayOutputStream()
        appCmdProcess.waitForProcessOutput(oStream, eStream)
        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
    }
}
