/*
 * 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.helper.ResourceHelper
import com.urbancode.air.plugin.iisconfiguration.helper.AppCmdCLIHelper
import com.urbancode.air.plugin.iisconfiguration.helper.PowerShellHelper
import org.codehaus.jettison.json.JSONObject
import org.codehaus.jettison.json.JSONArray
import groovy.util.AntBuilder
import com.urbancode.air.plugin.iisconfiguration.Globals
import com.urbancode.air.plugin.iisconfiguration.Util
import groovy.io.FileType

println("Starting configure...")
final File PLUGIN_HOME = new File(System.getenv().get("PLUGIN_HOME"))
String DISCOVERY_PS_SCRIPT = "${PLUGIN_HOME.getCanonicalPath()}\\fullDiscovery.ps1"

//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 resourceHelper = new ResourceHelper(ucdUri, ucdUsername, ucdPassword)
def thisResourcePath = props['resourcePath']
def configOutputFolder = props['configOutputFolder']
def resourceRoleName = props['resourceRoleName']
def resourceName = props['resourceName']

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

//MAIN FUNCTION
def main = {
    //retrieve srcType and srcPath
    def srcTypeAndPath = Util.formatPathAndTypeFromResourceRoleName(resourceRoleName, thisResourcePath)
    srcType = srcTypeAndPath['type']
    srcPath = srcTypeAndPath['path']
    def isIgnoreErrors = false

    //run msdeploy to perform package sync
    //example: msdeploy -verb:sync -source:webServer -dest:package=C:\testingArchive.zip
    msDeployHelper.runMSDeployScript(webDeployPath, verb, srcType, destType, srcPath, "\"${destPath}\"", argStrings, isIgnoreErrors)

    //unzip the config we just created so we can insert our metadata
    def configOutputFolderFile = new File(configOutputFolder)
    antBuilder.unzip(   dest:configOutputFolderFile.getCanonicalPath(),
                        src:destPath,
                        overwrite:"true" )

    //insert metadata
    def configOutputFolderName = configOutputFolder
    if (configOutputFolder.contains("/") || configOutputFolder.contains("\\")){
       configOutputFolderName = (configOutputFolder =~ /.*\/(.*)/)[0][1]
    }
    Properties metaData = new Properties()
    File metaDataFile = new File("${configOutputFolderFile.getCanonicalPath()}\\${Globals.UCD_METADATA_FILE_NAME}")
    metaData.setProperty(Globals.PROPERTY_RESOURCE_ROLE, resourceRoleName)
    metaData.setProperty(Globals.PROPERTY_CONFIG_FOLDER, configOutputFolderName)
    metaData.setProperty(Globals.PROPERTY_SRCPATH, srcPath)
    metaData.setProperty(Globals.PROPERTY_SRCTYPE, srcType)
    metaData.store(metaDataFile.newWriter(), null)

    //cleanup zip
    new File(destPath).delete()
}

//on y va!
main()