/*
* 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 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)
osh.login(url, username, password, token, insecure.toBoolean())

// Deploy application
def args = []
args << 'tag'
args << '--alias=' + alias.toBoolean()
if (!type.equals('none')) {
    args << '--source=' + type
}
args << source
dest.split(' ').each { destination ->
    if (destination.size() > 0) {
        args << destination
    }
}
osh.runCommand("[Action] Tagging ${dest} with ${source}...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        if (serr.contains('error: --source=ImageStreamTag requires a valid <name>:<tag> in SOURCE')) {
            println ("[Error] The ImageStreamTag requires a valid <name>:<tag> in SOURCE.")
            println ('[Possible Solution] Please update the step configuration with a valid Source Name of the form ' +
                     "<name>:<tag> for the ${type} Source Type.")
        }
        else if (serr.contains('error: --source=ImageStreamImage requires a valid <name>@<id> in SOURCE')) {
            println ("[Error] The ImageStreamImage requires a valid <name>@<id> in SOURCE.")
            println ('[Possible Solution] Please update the step configuration with a valid Source Name of the form ' +
                     "<name>@<id> for the ${type} Source Type.")
        }
        else if (serr.contains("error: invalid source \"${type}\";")) {
            println ("[Error] Invalid source type ${type} .")
            println ('[Possible Solution] Please update the step configuration with a valid Source Type. Valid values are ' +
                      'imagestreamtag, imagestreamimage, or docker.')
        }
        else if (serr.contains('error: only Docker images can have importing flags set')) {
            println ('[Error] Only Docker images can have importing flags set.')
            println ('[Possible Solution] Please update the step configuration to only have Insecure Import checked if ' +
                     'tagging Docker images. Otherwise leave Insecure Import unchecked.')
        }
        else {
            println ('[Error] Could not tag images.')
            println (serr)
            println (sout)
        }
        System.exit(1)
    }
    else {
        println ('[Ok] Successfully tagged image.')
        println (sout)
    }
}
