/*
* 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 deployment   = inProps['deployment'].trim()
String version      = inProps['version'].trim()
String scaling      = inProps['scaling']
String strategy     = inProps['strategy']
String triggers     = inProps['triggers']
String dryrun       = inProps['dryrun']
String output       = inProps['output']

// 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)

// Rollback deployment
def args = []
args << 'rollback'
args << deployment
if (version) {
    args << '--to-version=' + version
}
if (scaling.toBoolean()) {
    args << '--change-scaling-settings'
}
if (strategy.toBoolean()) {
    args << '--change-strategy'
}
if (triggers.toBoolean()) {
    args << '--change-triggers'
}
if (dryrun.toBoolean()) {
    args << '--dry-run'
}
else if (output && !output.equals('none')) {
    args << '--output=' + output
}

osh.runCommand("[Action] Executing Rollback Operation...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        if (serr.contains("error: ${deployment} is not a valid deployment or deploymentconfig")) {
            println ("[Error] ${deployment} is not a valid deployment or deployment config.")
            println ('[possible solution]  Please update the step configuration with a valid Deployment Name/Config.')
        }
        else {
            println ('[Error] Rollback operation failed.')
            println (serr)
            println (sout)
        }
        System.exit(1)
    }
    else {
        println ('[Ok] Rollback operation succeeded.')
        println (sout)
    }
}
