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

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() > 1){
            //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}"
        }

        if(srcType) {
            def source = '-source:' + srcType
            if(srcPath) {
                source = source + '=' + "\"" + srcPath + "\""
            }
            commandArgs << source
        }

        if(destType) {
            def dest = '-dest:' + destType
            if(destPath) {
                dest = dest + '=' + destPath
            }
            commandArgs << dest
        }

        //optional arguments need to be concatenated without a space on the end
        def command = commandArgs.join(' ') + argStrings
        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()
    }
}
