/*
* 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.helper.MSDeployCmdLineHelper
import org.codehaus.jettison.json.JSONObject
import org.codehaus.jettison.json.JSONArray
import com.urbancode.air.plugin.iisconfiguration.helper.ResourceHelper
import com.urbancode.air.plugin.iisconfiguration.Globals

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

//initialize ucd related variables
def ucdUsername = apTool.getAuthTokenUsername()
def ucdPassword = apTool.getAuthToken()
def ucdUri = new URI(System.getenv("AH_WEB_URL"))
def resourceHelper = new ResourceHelper(ucdUri, ucdUsername, ucdPassword)
def rootResourcePath = props['resourcePath']

//initialize iis related variables
def wwwRootPath = Globals.DEFAULT_WWWROOT_PATH
File wwwRootPathDir = null
if (props['wwwRootPath']){
  wwwRootPath = props['wwwRootPath']
}
wwwRootPathDir = new File(wwwRootPath)

//checks the registry for a certain key that IIS installs
def checkIISExists = {
    println("Verifying IIS installation...")
    def iisCheckCmdArgs = ["REG", "QUERY", "HKLM\\Software\\Microsoft\\InetStp"]
    println("Querying registry for IIS installation with command: \"${iisCheckCmdArgs.join(" ")}\"")

    def exitValue = -1
    try {
        def iisCheckProcess = iisCheckCmdArgs.join(" ").execute()
        iisCheckProcess.waitFor()
        exitValue = iisCheckProcess.exitValue()
    }
    catch (Exception e){
        println("Error found when attempting to search for IIS installation: \n${e}")
    }

    //if exitValue == 0, we successfully found the registry key coupled with IIS installations
    //1 means IIS is not installed since there is no key
    if(exitValue){
        println("IIS is not enabled on this machine. Please enable IIS and Web Deploy before continuing.")
        System.exit(0)
    }
    else {
        println("IIS installation found! Running auto-discovery...")
    }
}

def main = {
    checkIISExists()

    //---if we are here then IIS is installed on this agent's machine---
    //create root resource
    def iisRootResourcePath = "${rootResourcePath}/${Globals.WEBSERVER_RESOURCE_NAME}"
    def iisRootResourceDescription = "Root resource which all IIS resources will be children of"
    def iisRootResourceName = Globals.WEBSERVER_RESOURCE_NAME
    def iisRootResource = resourceHelper.getOrCreateSubResource(iisRootResourcePath, rootResourcePath, iisRootResourceName, iisRootResourceDescription)
    println("Created iisRootResource: ${iisRootResource}")

    //add role to above resource
    def roleProperties = [
        "iis.wwwroot.path": wwwRootPath,
        "iis.webDeployPath": Globals.WEB_DEPLOY_PATH_DEFAULT,
        "iis.appCmdFile": Globals.APP_CMD_FILE_DEFAULT,
        "iis.webserver.name": iisRootResourceName
    ]
    resourceHelper.addRoleToResource(iisRootResource, Globals.ROOT_ROLE_NAME, roleProperties)
    println("Added roles ${roleProperties} to resource ${iisRootResource}")
}

//go
main()
