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

class MSDeployCmdLineHelper {

    public String runMSDeployScript(def cmdPath, def verb, def srcType, def destType, def srcPath, def destPath, def argStrings, def isIgnoreErrors) {
        def commandArgs = ["\"" + cmdPath + "msdeploy.exe\"", "-verb:" + verb]
        //if there are optional arguments, format them so they can be added on the end of the command
        if(argStrings.size() > 0){
            //remove any commas with spaces and replace with just a comma
            //then put a comma before the args so it's formatted for msdeploy
            argStrings = argStrings.replaceAll(", ", ",")
            argStrings = ",${argStrings}"
        }

        //prepare the source portion of the msdeploy command
        def source = '-source:' + srcType
        if (srcPath){
            source = source + '=' + "\"" + srcPath + "\""
        }
        //if there are opt args then place them immediately after the package command
        if(srcType == Globals.TYPE_PACKAGE && argStrings.size() > 0){
            source = source + argStrings
        }
        commandArgs << source

        //prepare the destination portion of the msdeploy command
        def dest = '-dest:' + destType
        if (destPath){
           dest = dest + '=' + destPath
        }
        //if there are opt args then place them immediately after the package command
        if(destType == Globals.TYPE_PACKAGE && argStrings.size() > 0){
            dest = dest + argStrings
        }
        commandArgs << dest

        def command = commandArgs.join(' ')
        println("command: " + command)
        def proc = Runtime.getRuntime().exec(command)
        def out, errorOut
        proc.waitForProcessOutput(out, errorOut)

        if (proc.exitValue()) {
            if(isIgnoreErrors){
                println("Command failed with exit code: ${proc.exitValue()}\nand message: ${out}\n${errorOut}")
            }
            else {
                throw new Exception("Command failed with exit code: ${proc.exitValue()}\nand message: ${out}\n${errorOut}")
            }
        }
        return proc.exitValue()
    }
}
