/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. 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.CommandHelper
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

final def out = System.out
final def workDir = new File('.').canonicalFile

def queues = props['queues']
def transQueues = props['transQueues']
final def scriptFile = new File(workDir, 'create_queues.vbs')

def cscriptExe = "cscript.exe"
if (new File("C:\\Windows\\SysWOW64").exists()) {
    cscriptExe = "C:\\Windows\\SysWOW64\\cscript.exe"
}

//------------------------------------------------------------------------------
// Generate VB Script
//------------------------------------------------------------------------------

scriptFile.withPrintWriter { writer ->
    writer.println "On Error Resume Next"
    queues?.split('\n')?.each {
        writer.println "set mq = CreateObject(\"MSMQ.MSMQQueueInfo\")"
        writer.println "mq.PathName=\"$it\""
        writer.println "WScript.Echo \"Creating non-transactional queue $it\""
        writer.println "mq.Create False"
        writer.println "If Err <> 0 Then"
        writer.println "\tWScript.Echo \"Queue already exists!\""
        writer.println "\t Err.Clear"
        writer.println "End If"
    }

    transQueues?.split('\n')?.each {
        writer.println "set mq = CreateObject(\"MSMQ.MSMQQueueInfo\")"
        writer.println "mq.PathName=\"$it\""
        writer.println "WScript.Echo \"Creating transactional queue $it\""
        writer.println "mq.Create True"
        writer.println "If Err <> 0 Then"
        writer.println "\tWScript.Echo \"Queue already exists!\""
        writer.println "\t Err.Clear"
        writer.println "End If"
    }
}


//------------------------------------------------------------------------------
// Build the command
//------------------------------------------------------------------------------

try {
    new CommandHelper(workDir).runCommand("Execute queue creation script", [cscriptExe, '/nologo', scriptFile] as String[])
}
catch (Exception e) {
    println "Error executing queue creation script: ${e.message}"
    System.exit 1
}
finally {
    scriptFile.delete()
}

System.exit 0
