/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2017. 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.kubernetes.KubernetesHelper
 import com.urbancode.ud.client.ResourceClient

 // Get step properties
 AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
 Properties inProps   = apTool.getStepProperties()
 String chart         = inProps['chart']?.trim();
 String version       = inProps['version']?.trim();
 String releaseName   = inProps['releaseName']?.trim();
 String flags         = inProps['flags']?.trim();
 String serverUrl     = inProps['serverUrl']?.trim();
 String resourceId    = inProps['resourceId']?.trim();
 String path          = inProps['path'].trim();
 String kubeconfig    = inProps['kubeconfig'].trim();

 // Set up helper
 if (!path) {
   path = "helm"
 }
 File workDir = new File(".").canonicalFile
 KubernetesHelper kh = new KubernetesHelper(workDir, path)
 if (kubeconfig) {
   kh.addEnvironmentVariable("KUBECONFIG", kubeconfig);
 }

 // Step specific commands
 ArrayList args = []
 args << 'install'
 args << chart
 if (version) {
   args << '--version'
   args << version
 }
 if (releaseName) {
   args << '--name'
   args << releaseName
 }
 kh.setFlags(args, flags)
 output = (kh.getOutputFromCommand('[action] Installing chart ' + chart, args, 'Chart ' + chart + ' installed', 'Could not install chart ' + chart)) 

 // get the release name returned by Helm (especially needed if user chose to let helm generate a name for them)
 // we assume the first line returned from helm is in the format NAME: releaseName
 outputArray = output.split("\n");
 firstLine = outputArray[0];
 returnedreleaseName = firstLine.substring(5).trim()
 println "[info] The release is named " + returnedreleaseName

 // set the release name as an output property
 apTool.setOutputProperty("helm.release", returnedreleaseName);
 apTool.setOutputProperties();

 // update the resource role property to store the release name, if desired
 if (resourceId) {
   serverUri = KubernetesHelper.stringToUri(serverUrl)
   username = apTool.getAuthTokenUsername()
   password = apTool.getAuthToken()
   ResourceClient resourceClient = new ResourceClient(serverUri,  username, password)
   resource = resourceClient.getResourceById(resourceId)
   resourceClient.setResourceRoleProperty(resource.name, resourceId, "helm.release", returnedreleaseName)
   println "[info] Resource role property helm.release has been set to " + returnedreleaseName
 }

