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

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('resourceRoleName')
    configOutputFolder = metaData.getProperty('configOutputFolder')
    destSrcandDestType = Util.formatPathAndTypeFromResourceRoleName(resourceRoleName, resourcePath)
    destPath = destSrcandDestType['path']
    destType = destSrcandDestType['type']

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

main()
