/*
 * 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){
            // start of msdeploy command compliance
            // operations handled by msdeploy.exe v7.1.1764.0.  Operations should be preceded by '-'
            def msOpSettings = [ "-verb", "-source", "-dest", "-declareParam", "-setParam", "-setParamFile",
                "-declareParamFile", "-removeParam", "-disableLink", "-enableLink", "-disableRule",
                "-enableRule", "-replace", "-retryAttempts", "-retryInterval", "-skip", "-disableSkipDirective",
                "-eableSkipDirective", "-verbose", "-whatif", "-disableAppStore", "-xpath", "-xml ",
                "-allowUntrusted", "-showSecure", "-preSync", "-postSync" ]
            def opsnum = msOpSettings.size()

            // Does input argStrings constain operations?
            println "Options String: " + argStrings
            for (int i=0; i<opsnum; i++) {
                if ( argStrings.contains(msOpSettings[i]) ) {
                    /* if an operation is found, make sure there is whitepace before the operation names
                     * particularly those in the middle of the string*/
                    argStrings = argStrings.replace(msOpSettings[i], " "+msOpSettings[i] )
                }
            }
            println argStrings

            //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(", ", ",") // remove space after commas
            argStrings = argStrings.replaceAll(" ,", ",") // remove space before commas

            // remove the leading and trailing white spaces so that the need for starting comma
            // could be checked if needed.
            argStrings = argStrings.trim()

            // if the first character is '-' place a whitespace as the leading char.
            if ( argStrings.charAt(0) == '-') {
                argStrings = " ${argStrings}"
            }
            else if ( !(argStrings.charAt(0) == ',') ) {
                argStrings = ",${argStrings}"
            }
            // print the final argStrings
            println "Optional args: "
            println argStrings
        }
        // end of msdeploy command compliance

        //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)
        proc.waitForProcessOutput(System.out, System.err)

        if (proc.exitValue()) {
            if(isIgnoreErrors){
                println("IIS Configure Plugin: Attempted msdeploy command and failed")
            }
            else {
                throw new Exception("IIS Configure Plugin: Attempted msdeploy command and failed")
            }
        }
        return proc.exitValue()
    }
}
