/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2023. 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.AirPluginTool
import com.urbancode.air.plugin.argocd.ArgoCDHelper
import com.urbancode.air.plugin.argocd.Inventory
import org.apache.log4j.Level
import org.apache.log4j.Logger

import groovy.yaml.YamlSlurper

// Get step properties
def apTool   = new AirPluginTool(args[0], args[1])
def inProps  = apTool.getStepProperties()

/*
 * We acquire the specified log4j level from the input properties and set the root logger level.
 * This will set the logger level for all loggers retrieved in this step.
 * If the logger level specified is invalid, we default to INFO.
 */
String logLevel = inProps['loggerLevel']
Logger.getRootLogger().setLevel(Level.toLevel(logLevel, Level.INFO))
Logger logger = Logger.getLogger(getClass())

String application = inProps['application']?.trim()
String flags       = inProps['flags']?.trim();
String cmdpath     = inProps['cmdpath']?.trim();
boolean waitonhealth = inProps['waitonhealth']?.trim()?.toBoolean();
Integer healthtimeout = inProps['waitonhealthtimeout']?.trim()?.toInteger();

// Set up helper
File workDir = new File(".").canonicalFile
ArgoCDHelper acdh = new ArgoCDHelper(workDir, cmdpath)

/*
 * Need to check that we were given application name
 */
if (!application) {
    println('[Error] The step requires an application name be given')
    System.exit(1)
}

// Get information about the application
def args = []
args << 'app'
args << 'get'

if (application) {
    args << application
}

/*
 * Run the 'app get' command.  The post-processing steps will parse the sync
 * and health status from the output and create output properties with those
 * values.
 */
acdh.setFlags(args, flags)
boolean getAppStatus = true
String sout, serr
String healthStatus = ""
Date startTime = new Date()
Long stopTime = startTime.getTime() + (healthtimeout * 1000)
while (getAppStatus) {

    acdh.runCommand("[Action] Getting info about application...", args) { Process proc ->
        (sout, serr) = acdh.captureCommand(proc)
        String[] lines = sout.split('\n')
        for (String line : lines) {
            if (line.matches("Health Status:(.*)")) {
                healthStatus = line.split(':')[1].trim()
                break
            }
        }
        println("Current health status: " + healthStatus)
    }

    /* Check if we need to run the app-get again. */
    getAppStatus = false
    if (healthStatus.equals("Progressing") && waitonhealth) {
        Date currentTime = new Date()
        //printf("Healthtimeout: %d\n", healthtimeout)
        //printf("currentTime: %d\tstopTime: %d\n", currentTime.getTime(), stopTime)
        if (currentTime.getTime() < stopTime)
            getAppStatus = true
    }

    /* If not continuing, print out stderr and stdout.
     * Else sleep() before trying again.
     */
    if (!getAppStatus) {
        println ('[Stderr output]')
        println (serr)
        println ('[Stdout output]')
        println (sout)
    }
    else
        sleep(15000)
}

