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

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

def final SOURCE_PATH = "C:\\inetpub\\wwwroot\\"

//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 sourcePath = SOURCE_PATH
File sourcePathDir = null
if (props['sourcePath'] != null){
  sourcePath = props['sourcePath']
}
sourcePathDir = new File(sourcePath)
if (!sourcePathDir.exists()){
    println("Could not find directory at property sourcePath='${sourcePath}'. Please set the property sourcePath if IIS is not installed with default path of '${SOURCE_PATH}'")
    System.exit(0)
}

//---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 = [
    sourcePath: sourcePath,
]
resourceHelper.addRoleToResource(iisRootResource, Globals.ROOT_ROLE_NAME, roleProperties)
println("Added roles ${roleProperties} to resource ${iisRootResource}")
