/*
* 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 org.apache.commons.lang3.StringUtils

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 type        = inProps['type'].trim()
String name        = inProps['name'].trim()
String replicas    = inProps['replicas'].trim()

if (!StringUtils.isNumeric(replicas)) {
    println ('[Error] The value of the Number of Replicas property is not numeric.')
    println ('[Possible Solution] Please update the step configuration with a numeric value for Number of Replicas.')
    System.exit(1)
}

// 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 application
def args = []
args << 'scale'
args << '--replicas=' + replicas
args << type
args << name
osh.runCommand("[Action] Scaling ${name}...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        if (serr.contains("the server doesn't have a resource type \"${type}\"")) {
            println ("[Error] The server doesn't have a resource type ${type}.")
            println ('[Possible Solution] Please update the step configuration with a valid Resource Type.')
        }
        else if (serr.contains("\"${name}\" not found")) {
            println ("[Error] The server could not find resource ${name}.")
            println ('[Possible Solution] Please update the step configuration with a valid Resource Name.')
        }
        else {
            println ('[Error] Scaling failed.')
            println (serr)
            println (sout)
        }
        System.exit(1)
    }
    else {
        println ('[Ok] Resource scaled.')
        println (sout)
    }
}
