/*
 * 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 commandArgs = ["\"" + cmdPath + "msdeploy.exe\"", "-verb:" + verb]

        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
        }

        argStrings.each { arg -> commandArgs << arg }

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

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