/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2016. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2020. 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.openshift.OpenShiftHelper

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

String url          = inProps['url'].trim()
String username     = inProps['username']
String token        = inProps['token']
String insecure     = inProps['insecure']
String home         = inProps['home']?.trim()
String project      = inProps['project'].trim()
String flags        = inProps['flags']?.trim();
String template     = inProps['template'].trim()
String parameter    = inProps['parameter']?.trim()
String useApplyOrCreate = inProps['useApplyOrCreate']?.trim()

def checkInputCommand = useApplyOrCreate ==~ /^(?:apply|create)$/
if (!checkInputCommand) {
    println('[Error] Check input command, should be apply/create')
    System.exit(1)
}

// Set up helper
File workDir = new File(".").canonicalFile
OpenShiftHelper osh = new OpenShiftHelper(workDir, home)

def temp = File.createTempFile('temp', '.txt', workDir)
temp.deleteOnExit()

def args = []
def params = []

// Get available parameters from template, if parameter file is given
if (parameter) {
    args << 'process'

    if (url) {
        args << '--server=' + url
    }

    if(project) {
        args << '--namespace=' + project
    }

    if (username) {
        args << '--user=' + username
    }

    if (token) {
        args << '--token=' + token
    }

    if (insecure.toBoolean()) {
        args << '--insecure-skip-tls-verify'
    }

    args << '-f'
    args << template
    args << '--parameters'
    osh.runCommand("[Action] Looking for parameters to replace...", args) { Process proc ->
        def (String sout, String serr) = osh.captureCommand(proc)
        println (serr)
        if (sout) {
            println ('[Ok] Available parameters found.')
            println (sout)
            def lines = sout.split('\n')
            lines.each { line ->
                params << (line.split(" "))[0]
            }
        }
    }
}

// Process template into resource list
args = []
args << 'process'

if (url) {
    args << '--server=' + url
}

if(project) {
    args << '--namespace=' + project
}

if (username) {
    args << '--user=' + username
}

if (token) {
    args << '--token=' + token
}

if (insecure.toBoolean()) {
    args << '--insecure-skip-tls-verify'
}

args << '-f'
args << template
// Add parameter name=value if present in both the parameters file and the template
if (parameter) {
    def fileContents = new File(parameter).text.split('\n')
    fileContents.each { line ->
        params.each { param ->
            if (line.substring(0, line.indexOf("=")) == param) {
                println line
                args << line
            }
        }


    }
}
osh.runCommand("[Action] Executing Process Operation...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    println (serr)
    if (sout) {
      println (sout)
      temp << sout
    }
}

// Apply or Create objects from resource list
def applyArgs = []
applyArgs << useApplyOrCreate

if (url) {
    applyArgs << '--server=' + url
}

if(project) {
    applyArgs << '--namespace=' + project
}

if (username) {
    applyArgs << '--user=' + username
}

if (token) {
    applyArgs << '--token=' + token
}

if (insecure.toBoolean()) {
    applyArgs << '--insecure-skip-tls-verify'
}

applyArgs << '-f'
applyArgs << temp.getAbsolutePath()
osh.setFlags(applyArgs, flags)
osh.runCommand("[Action] Executing " + useApplyOrCreate + " Operation...", applyArgs) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    println (serr)
    println (sout)
}