/*
* Licensed Materials - Property of HCL
* UrbanCode Build
* (c) Copyright HCL Technologies Ltd. 2019. All Rights Reserved.
*/
import com.urbancode.air.AirPluginTool
import com.urbancode.air.ExitCodeException
import com.urbancode.build.plugin.ucd.rest.AppProcessRequest
import com.urbancode.build.plugin.ucd.rest.UCDRestHelper

import org.apache.log4j.Level
import org.apache.log4j.Logger

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final File workDir = new File('.').canonicalFile
final AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = apTool.getStepProperties()

String ucdUrl = props['automation/url']
String ucdUser = props['automation/user']
String ucdPassword = props['automation/passScript'] ?: props['automation/password']

String ucdAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']

boolean skipWait = Boolean.valueOf(props['skipWait'])
long timeout = props['timeout'] ? Long.valueOf(props['timeout']) : -1

/*Configure Log4j logger */
String logLevel = props['loggerLevel']
Logger.getRootLogger().setLevel(Level.toLevel(logLevel)) // Configure log level for all loggers
Logger logger = Logger.getLogger(getClass()) // Get the logger for this class

UCDRestHelper ucdHelper = new UCDRestHelper(ucdUrl, ucdUser, ucdPassword, ucdAuthToken)

logger.info("Initializing deployment.")

/* Configure application process request */
AppProcessRequest appProcessRequest = new AppProcessRequest(props)

String processId
try {
    processId = ucdHelper.deploy(appProcessRequest)
}
 catch (ExitCodeException ex) {
     logger.error(ex.getMessage())
     System.exit(1)
 }

 if (!skipWait) {
     logger.info("Waiting for process with ID ${processId} to complete.")
     try {
         ucdHelper.waitForProcess(processId, timeout)
     }
     catch (ExitCodeException ex) {
         logger.error(ex.getMessage())
         System.exit(1)
     }

     logger.info("Process completed successfully.")
 }
 else {
     logger.info("Successfully initiated process.")
 }

 apTool.setOutputProperty("processId", processId)
 apTool.storeOutputProperties()
