/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2014, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. 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 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()

final def REPO_PATH_SEPARATOR = "/"

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 = Boolean.valueOf(inProps['allowInsecure'])
String identityKey = inProps['identityKey'].trim()

//remove trailing slashes from url
while (url.endsWith(REPO_PATH_SEPARATOR)) {
    url = url.substring(0, url.length() - 1)
}
//remove trailing slashes from path
while (path.endsWith(REPO_PATH_SEPARATOR)) {
    path = path.substring(0, path.length() - 1)
}

String proxyHost = inProps['proxyHost']?.trim()
String proxyPort =  inProps['proxyPort']?.trim()
String proxyPass = inProps['proxyPass']?.trim()
String proxyUser = inProps['proxyUser']?.trim()

ArtifactoryHelper aHelper = new ArtifactoryHelper(username, password, apiKey, allowInsecure, proxyHost, proxyPort, proxyPass, proxyUser, identityKey)
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
}