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

String source        = inProps['source'].trim()
String dest          = inProps['dest'].trim()
String alias         = inProps['alias']
String type          = inProps['type']

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

// Deploy application
def args = []
args << 'tag'

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

args << '--alias=' + alias.toBoolean()
if (!type.equals('none')) {
    args << '--source=' + type
}
args << source
dest.split(' ').each { destination ->
    if (destination.size() > 0) {
        args << destination
    }
}

osh.setFlags(args, flags)

osh.runCommand("[Action] Tagging ${dest} with ${source}...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    println (serr)
    println (sout)
}
