/*
* 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.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.openshift.OpenShiftHelper

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

String url          = props['url'].trim()
String username     = props['username']
String password     = props['password']
String token        = props['token']
String insecure     = props['insecure']
String home         = props['home'].trim()
String project      = props['project'].trim()

String config       = props['config'].trim()
String patchJSON    = props['patchJSON'].trim()

if (!patchJSON.contains("\r") && !patchJSON.contains("\n")) {
    def patchJsonFile = new File(patchJSON)
    if (patchJsonFile.exists()){
        patchJSON = patchJsonFile.text
    }
}


// Set up helper
File workDir = new File(".").canonicalFile
OpenShiftHelper osh = new OpenShiftHelper(workDir, home)
osh.login(url, username, password, token, insecure.toBoolean())
osh.setProject(project)

// Deploy
def args = []
args << 'patch'
args << "dc/$config"
args << "-p"
args << patchJSON

osh.runCommand("[Action] Executing Patch Operation...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        println ('[Error] Patch operation failed.')
        println (serr)
        println (sout)
        System.exit(1)
    }
    else {
        println ('[Ok] Patch operation succeeded.')
        println (sout)
    }
}