/*
* 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 inProps  = apTool.getStepProperties()

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

String config       = inProps['config'].trim()
String type         = inProps['type']

// 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 << 'deploy'
args << config
if (type.equals('latest')) {
    args << '--latest'
}
else if (type.equals('retry')) {
    args << '--retry'
}
else if (type.equals('cancel')) {
    args << '--cancel'
}
else if (type.equals('triggers')) {
    args << '--enable-triggers'
}
// N.B.: To view latest deployment, simply do not include any -- option

osh.runCommand("[Action] Executing Deployment Operation...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        if (serr.contains("Error from server: deploymentconfigs \"${config}\" not found")) {
            println ("[Error] Deployment Config \"${config}\" not found.")
            println ('[Possible Solution] Please update the step configuration with a valid Deployment Config.')
        }
        else if (serr.contains('; only failed deployments can be retried.')) {
            println ('[Error] Previous deployment completed, only failed deployments can be retried.')
            println ('[Possible Solution] A new deployment can be started by selecting "New Deployment" as the Deployment ' +
                     'Action in the step configuration.')
        }
        else {
            println ('[Error] Deployment operation failed.')
            println (serr)
            println (sout)
        }
        System.exit(1)
    }
    else {
        println ('[Ok] Deployment operation succeeded.')
        println (sout)
    }
}