/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2016, 2017. 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.plugin.wldeploy.WebLogicStatusHelper

final def workDir = new File('.').canonicalFile
AirPluginTool apTool = new AirPluginTool(args[0], args[1])
def props = apTool.getStepProperties(System.getenv("UCD_SECRET_VAR"))
final def inputPropsFile = new File(args[0])
final def inputPropsStream = null
try {
    inputPropsStream = new FileInputStream(inputPropsFile)
    props.load(inputPropsStream)
}
catch (IOException e) {
    throw new RuntimeException(e)
}

Properties outProps = new Properties()

final def jmxUrl = props['jmxUrl']
def user = props['user']
def pass = props['password']
final def configFile = props['configFile']
final def keyFile = props['keyFile']
def targets = props['targets']

targets = targets.split(',')

try {
    WebLogicStatusHelper helper = new WebLogicStatusHelper()
    if (configFile) {
        user = helper.getUser(configFile, keyFile)
        pass = helper.getPass(configFile, keyFile)
    }
    helper.initConn(jmxUrl, user, pass)
    targets.each { target ->
       println "getting apps for $target"
       String appList = helper.getAppsForTarget(target)
       outProps.setProperty("apps-$target", appList)
    }

    helper.closeConn()

}
catch (Exception e) {
    e.printStackTrace()
    throw e
}

final OutputStream outputPropsStream = null
try {
    outputPropsStream = new FileOutputStream(new File(args[1]))
    outProps.store(outputPropsStream, "")
}
finally {
    if (outputPropsStream != null) {
        outputPropsStream.close()
    }
}
