/*
* 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. 2024. 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 org.apache.log4j.Level
import org.apache.log4j.Logger

// 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 flags       = inProps['flags']?.trim();
String cmdpath     = inProps['cmdpath']?.trim();

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

// Create the ApplicationSet list command string
def args = []
args << 'appset'
args << 'list'

/*
 * Run the 'appset list' command.
 */
acdh.setFlags(args, flags)
acdh.runCommand("[Action] List applicationset...", args) { Process proc ->
    def (String sout, String serr) = acdh.captureCommand(proc)
    println ('[Stderr output]')
    println (serr)
    println ('[Stdout output]')
    println (sout)
}

/*
 * Run the 'appset list' command again with the -o name option to get the names of the appsets so they can be returned as output
 * properties.  The command is explicitly run a second time because we cannot control the output flag chosen by the user for the
 * initial invocation.  In order to have a known output format to parse, we run the command a second time with the "-o name" option.
 */
def args2 = []
args2 << 'appset'
args2 << 'list'
args2 << '-o'
args2 << 'name'
//acdh.setFlags(args2, flags)

def appsetNamesList = []
acdh.runCommand("[Action] List applicationset to get appset names...", args2) { Process proc ->
    def (String sout, String serr) = acdh.captureCommand(proc)
    println ('[Stderr output]')
    println (serr)
    println ('[Stdout output]')
    println (sout)

    sout.eachLine( { String line ->
      appsetNamesList.add(line)
    })

    printf("ApplicationSet Names: %s\n", appsetNamesList.toString())
}





