/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* (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.artifactory.ArtifactoryHelper

// Get step properties
AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
Properties inProps = apTool.getStepProperties()

String url        = inProps['url'].trim()
String username   = inProps['username']
String password   = inProps['password']
String apiKey     = inProps['apiKey'].trim()
String path       = inProps['path'].trim()
String properties = inProps['properties'].trim()
boolean recursive = inProps['recursive'].toBoolean()
boolean allowInsecure = (inProps['allowInsecure']?:"false").toBoolean()

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey, allowInsecure)
String propertiesPath = pathFromProps(properties, recursive)
String propertiesUrl = aHelper.getCombinedUrl(url, "api/storage/${path}/${propertiesPath}")
println ("[action]  Setting item ${path} properties to ${propertiesPath}...")
def set = aHelper.put(propertiesUrl)
if (!set) {
    println ("[error]  Could not set properties.")
    System.exit(1)
}
else {
    println ('[ok]  Properties set.')
    System.exit(0)
}

/**
*  Convert a new-line separated list of properties to the proper REST endpoint form to append to the URL
*  @param properties A new-line separated list of properties to convert to URL format
*  @param recursive False to add the prevent recursion path to the REST endpoint, false to leave out and recurse by default
*/
private String pathFromProps(String properties, boolean recursive) {
    String path = '?properties='
    properties.split('\n').each() { property ->
        path += property + '|'
    }
    path = path.substring(0, path.length() - 1)    // remove last unneccesary pipe
    if (!recursive) {
        path += '&recursive=0'
    }
    return path
}