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

import com.urbancode.air.AirPluginTool
import com.urbancode.ud.client.SystemClient
import com.urbancode.ubuild.ucbtool.UCBTool
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.codehaus.jettison.json.JSONObject
import groovy.xml.MarkupBuilder
import groovy.time.TimeDuration

//------------------------------------------------------------------------------
// 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')
String ucbAuthToken = System.getenv("AUTH_TOKEN")

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

// 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']

// Step properties
String tokenUsername = props['username']
String tokenDescription = props['description']
String scope = props['scope']
long tokenExpiration = new TimeDuration(0, Integer.parseInt(props['expiration'] as String), 0, 0).from.now.time

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

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("Retrieving user ID for user \"$tokenUsername\" in UCD.")
String userId = systemClient.getUserId(tokenUsername)
logger.info("User ID for user \"$tokenUsername\" is \"$userId\". Creating an auth token.")
JSONObject responsePayload = systemClient.createAuthToken(userId, tokenDescription, tokenExpiration)
String token = responsePayload.getString("token")

UCBTool ucbTool = new UCBTool()
Writer stringWriter = new StringWriter()
MarkupBuilder markupBuilder = new MarkupBuilder(stringWriter)
markupBuilder.properties {
    property(name: "ucdUserAuthToken", secure: true, token)
}

ucbTool.addProperties(webUrl, ucbAuthToken, buildLifeId, scope, stringWriter.toString(),
        "Creating secure auth token property at $scope scope")

apTool.storeOutputProperties()
