/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (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.
 */
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper
import com.urbancode.air.plugin.wldeploy.ResourceHelper

import org.apache.commons.io.FileUtils
import org.apache.commons.io.filefilter.NameFileFilter
import org.apache.commons.io.filefilter.DirectoryFileFilter

def apTool = new AirPluginTool(args[0], args[1])
def props = apTool.getStepProperties()
def isWindows = apTool.isWindows
def ch = new CommandHelper(new File('.').canonicalFile)
def isInstalled = false

def mwHome = props['mwHome'].trim()
def installPaths = []

// user set agent property wldeploy.mwHome
if (mwHome) {
    installPaths << mwHome
}
else {
    println("Searching for WebLogic installation using standard installation paths. You may override the standard installation path" +
        " by setting the 'wldeploy.mwHome' property on the agent pointing to your installation directory.")

    if (isWindows) {
        installPaths.addAll([
            "C:" + File.separator + "Program Files" + File.separator + "Oracle" + File.separator + "Middleware",
            "C:" + File.separator + "Program Files (x86)" + File.separator + "Oracle" + File.separator + "Middleware"
        ])
    }
    else {
        installPaths.addAll(["/opt/wls"])
    }
}

def webLogicJarPath = props['path']
if (webLogicJarPath) {
    def wlJarFile = new File(webLogicJarPath)
    if (!wlJarFile.exists() || !wlJarFile.isFile()) {
        println("Specified path: ${webLogicJarPath} is not a file on the file system.")
        webLogicJarPath = ""
    }
}
else {
    for (def path : installPaths) {
        println("Searching for 'weblogic.jar' on installation path: ${path}. You may override by specifying the 'wldeploy.path' property" +
            " on the agent pointing to the fully-qualified path of the WebLogic WLDeploy Ant Task JAR file or full client JAR file.")
        File installDir = new File(path)
        if (installDir.exists() && installDir.isDirectory()) {
            // search recursively for weblogic.jar
            def files = FileUtils.listFiles(installDir, new NameFileFilter("weblogic.jar"), DirectoryFileFilter.DIRECTORY)

            if (files) {
                webLogicJarPath = files[0].getAbsolutePath()
                println("Found weblogic jar file: ${webLogicJarPath}")
                break
            }
        }
        else {
            println("${path} is not a directory on the file system. ")
        }
    }
}

if (!webLogicJarPath) {
    println("No WebLogic installation found. Ending WebLogic Auto-Discovery process.")
    System.exit(0)
}

// ucd setup
def ucdUser = apTool.getAuthTokenUsername()
def ucdPass = apTool.getAuthToken()
def ucdUri = new URI(System.getenv("AH_WEB_URL"))
def ucdHelper = new ResourceHelper(ucdUri, ucdUser, ucdPass)

// create base resource in ucd
def rootResourcePath = props['resourcePath']
def subResourcePath = rootResourcePath + "/WebLogic-Installation"
def subResourceDescription = "WebLogic Installation used for auto-configuration. Empty properties will use resource properties."
def subResourceName = "WebLogic-Installation"
def subResource = ucdHelper.getOrCreateSubResource(subResourcePath, rootResourcePath, subResourceName, subResourceDescription)

def roleProperties = new HashMap<String,String>()
// role property not required if it is already set on the agent
if (props['wldeploy.path']) {
    roleProperties.put("wldeploy.path", webLogicJarPath) // installation role given path to jar property
}

ucdHelper.addRoleToResource(subResource, "WebLogic-Installation", roleProperties)