/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2014. 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.AirPluginTool;
import com.urbancode.air.CommandHelper;
import com.urbancode.air.plugin.websphere.bpm.WebSphereBPMHelper;

def processOfflinePackage(invoke, commandArgs, isWindows, ch) {
    def exitVal = 0
    try {
        File tempFile = new File("temp.py")
        tempFile.deleteOnExit()
        BufferedWriter temp = new BufferedWriter(new FileWriter(tempFile))
        temp.write(invoke, 0, invoke.length())
        temp.close()

        if (isWindows) {
            ch.addEnvironmentVariable("PROFILE_CONFIG_ACTION", "true")
        }
        ch.runCommand(invoke, commandArgs)

        tempFile.delete()
    } catch (Exception e) {
        e.printStackTrace()
        exitVal = 1
    }
    return exitVal
}

//////////////////////MAIN////////////////////////
final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def ch = new CommandHelper(new File("."))

final def props = apTool.getStepProperties()
final def isWindows = apTool.isWindows

final def workDir = new File('.').getCanonicalFile()
final def compName = new File(".").getCanonicalFile().name //this gets resolved to component name

def wsadmin = isWindows ? "wsadmin.bat" : "wsadmin.sh"

def port = props['port']
def user = props['user']
def host = props['host']
def password = props['password']
def connType = props['connType']
def profHome = props['profileRoot']
if (!(profHome.endsWith("\\") || profHome.endsWith("/"))) {
    profHome = profHome + File.separator
}
def commandPath = profHome + "bin" + File.separator + wsadmin
def commandArgs = [commandPath, "-lang", "jython"]
commandArgs << "-conntype"
commandArgs << connType.trim()
commandArgs << "-port"
commandArgs << port

if (!props['useSOAPProps'].equals("true")) {
    commandArgs << "-user"
    commandArgs <<  user
    commandArgs << "-password"
    commandArgs << password
}

if (host) {
    commandArgs << "-host"
    commandArgs << host
}

commandArgs << "-f"
commandArgs << "temp.py"

def containerSnapshotAcronym = props['containerSnapshotAcronym']
def containerTrackAcronym = props['containerTrackAcronym']
def containerAcronym = props['containerAcronym']
if (WebSphereBPMHelper.isEmpty(containerAcronym)) {
    containerAcronym = compName
}

containerAcronym = WebSphereBPMHelper.getContainerAcronym(containerAcronym, commandArgs)
containerSnapshotAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerSnapshotAcronym, containerAcronym, commandArgs)
containerTrackAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerTrackAcronym, containerAcronym, commandArgs)

def skipGovernance = props['skipGovernance']
def createInvokeArgs = '[ -containerAcronym ' + containerAcronym + ' -containerSnapshotAcronym ' + containerSnapshotAcronym + ' -containerTrackAcronym ' + containerTrackAcronym
def extractInvokeArgs = new String(createInvokeArgs)
if (!skipGovernance.equals("false")) {
    createInvokeArgs = createInvokeArgs + ' -skipGovernance ' + skipGovernance
}

def servers = props['servers']
def offlineServers = servers.split(",")
for (offlineServer in offlineServers) {
    createInvokeArgs = createInvokeArgs + ' -serverName ' + '"' + offlineServer + '"'
    def retCode = processOfflinePackage("AdminTask.BPMCreateOfflinePackage('" + createInvokeArgs + "]')", commandArgs, isWindows, ch)
    if (retCode == 0) {
        extractInvokeArgs = extractInvokeArgs + ' -serverName ' + '"' + offlineServer + '"'
        def packagePathString = workDir.toString() + File.separator + offlineServer + ".zip"
        packagePathString = packagePathString.replace('\\', '/')
        File packagedFile = new File(packagePathString)
        if (packagedFile.isFile()) {
            packagedFile.delete()
        }
        extractInvokeArgs = extractInvokeArgs + ' -outputFile ' + '"' + packagePathString + '"'
        retCode = processOfflinePackage("AdminTask.BPMExtractOfflinePackage('" + extractInvokeArgs + "]')", commandArgs, isWindows, ch)
        if (retCode != 0) {
            System.exit(retCode)
        }
    }
}
