/*
* 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 com.urbancode.air.plugin.iisconfiguration.Globals
 import com.urbancode.air.plugin.iisconfiguration.Util

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

 //initialize ucd related variables
 def ucdUsername = apTool.getAuthTokenUsername()
 def ucdPassword = apTool.getAuthToken()
 def ucdUri = new URI(System.getenv("AH_WEB_URL"))
 def resourcePath = props['resourcePath']
 resourcePath = (resourcePath =~ /(.*)\/.*/)[0][1]
 def resourceRoleName = ""
 def configOutputFolder = ""

//initialize iis variables
def msDeployHelper = new MSDeployCmdLineHelper()
def webDeployPath = props['webDeployPath']
def verb = "sync"
def srcType = "package"
def srcPath = new File("iisConfiguration.zip").getCanonicalPath()
def destType = ""
def destPath = ""
def argStrings = props['msDeployArgs']?.trim()

def main = {
    //format web deploy commands using meta data info
    def metaData = new Properties()
    def metaDataFile = Util.findFileRecursivelyByName(Globals.UCD_METADATA_FILE_NAME)

    //get UCD Metadata from folder so we can read it
    metaData.load(metaDataFile.newDataInputStream())
    resourceRoleName = metaData.getProperty(Globals.PROPERTY_RESOURCE_ROLE)
    configOutputFolder = metaData.getProperty(Globals.PROPERTY_CONFIG_FOLDER)
    destSrcandDestType = Util.formatPathAndTypeFromResourceRoleName(resourceRoleName, resourcePath)
    destPath = destSrcandDestType['path']
    destType = destSrcandDestType['type']
    def isIgnoreErrors = false

    //package files into zip so web deploy can sync it to the system
    antBuilder.zip(     destfile:srcPath,
                        basedir:configOutputFolder )

    //example: msdeploy -verb:sync -dest:appHostConfig="testing" -source:package=C:\testingArchiveZip.zip
    if (destPath){
        destPath = "\"${destPath}\""
    }
    msDeployHelper.runMSDeployScript(webDeployPath, verb, srcType, destType, srcPath, destPath, argStrings, isIgnoreErrors)
}

main()
