/*
* 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. 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']?.trim()
String token          = inProps['token']
String insecure       = inProps['insecure']
String home           = inProps['home']?.trim()
String project        = inProps['project']?.trim()
String flags          = inProps['flags']?.trim();
String serviceAccount = inProps['serviceAccount']
String appSecrets     = inProps['appSecrets']
String pullSecrets    = inProps['pullSecrets']

if (!appSecrets && !pullSecrets) {
    println('[Error] The step requires either App Secrets or Pull Secrets')
    System.exit(1)
}

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

// Apply
def args = []
args << 'patch'
args << 'sa'
args << serviceAccount
args << '-p'

def patchData

if (appSecrets) {
    def appSecretPatchData = []
    appSecrets.split("[\r\n]+").each() { appSecret ->
        appSecretPatchData << "{\"name\":\"${appSecret}\"}"
    }

    appSecretPatchList = appSecretPatchData.join(',')
    patchData = "\"secrets\":[${appSecretPatchList}]"
}

if (pullSecrets) {
    def pullSecretPatchData = []
    pullSecrets.split("[\r\n]+").each() { pullSecret ->
        pullSecretPatchData << "{\"name\":\"${pullSecret}\"}"
    }

    pullSecretPatchList = pullSecretPatchData.join(',')

    if (patchData) {
        patchData = patchData + ",\"imagePullSecrets\":[${pullSecretPatchList}]"
    }
    else {
        patchData = "\"imagePullSecrets\":[${pullSecretPatchList}]"
    }
}

patchData = "{${patchData}}"
args << patchData

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'
}

osh.setFlags(args, flags)

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