/*
* Licensed Materials - Property of HCL
* UrbanCode Build
* (c) Copyright HCL Technologies Ltd. 2019. All Rights Reserved.
*/

import java.text.SimpleDateFormat
import com.urbancode.air.AirPluginTool
import com.urbancode.ud.client.SystemClient
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.codehaus.jettison.json.JSONObject

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
File workDir = new File('.').canonicalFile
String javaHome = System.getenv('JAVA_HOME')
String pluginHome = System.getenv("PLUGIN_HOME")
String webUrl = System.getenv('WEB_URL')
String buildLifeId = System.getenv('BUILD_LIFE_ID')

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

// Configure Log4j logger
String logLevel = props['loggerLevel']
Logger.getRootLogger().setLevel(Level.toLevel(logLevel))
Logger logger = Logger.getLogger(getClass())

// The auth token potentially created by CreateAuthToken.groovy
String ucdUserAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"]
if (ucdUserAuthToken) {
    // Automation properties
    String ucdUrl = props['automation/url']
    String ucdUser = props['automation/user']
    String ucdPassword = props['automation/passScript'] ?: props['automation/password']
    String ucdAuthToken = props['automation/authToken']

    SystemClient systemClient
    if (ucdAuthToken) {
        systemClient = new SystemClient(new URI(ucdUrl), "PasswordIsAuthToken", ucdAuthToken, true)
    } else {
        systemClient = new SystemClient(new URI(ucdUrl), ucdUser, ucdPassword, true)
    }

    logger.info("Deleting auth token in UCD...")
    systemClient.deleteAuthToken(ucdUserAuthToken)
}
else {
    logger.info("No UCD user auth tokens were found to delete.")
}