/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import com.urbancode.air.CommandHelper
import com.urbancode.air.AirPluginTool
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

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

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

if(!mwHome) {
    mwHome = System.getenv("MW_HOME")?.trim()
    if (mwHome) {
        println("[OK] Found environment variable 'MW_HOME=${mwHome}'.")
    }
}

// user set agent property wldeploy.mwHome or MW_HOME environment variable
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, or by setting the 'MW_HOME'" +
        " environment variable on your agent.")

    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>()
if (webLogicJarPath) {
    roleProperties.put("wldeploy.path", webLogicJarPath) // installation role given path to jar property
}

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