/*
 * 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.CommandHelper

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

  // Set up helper
 File workDir = new File(".").canonicalFile
 ch = new CommandHelper(workDir)

 // Initialize Container Service plug-in
 ArrayList argsInit = []
 argsInit << "bx"
 argsInit << "cs"
 argsInit << "init"
 String message = "[action] Running command to initialize Container Service plug-in.";
 ch.runCommand(message, argsInit, { proc ->
   proc.out.close() // close stdin
   proc.consumeProcessErrorStream(System.out) // forward stderr
   result = proc.text.trim();
 })
 println "[ok] Command returned " + result

 // Get the cluster config from IBM Cloud
 ArrayList args = []
 args << "bx"
 args << "cs"
 args << "cluster-config"
 args << cluster
 message = "[action] Running command to download Kubernetes configuration data and certificates to connect to your cluster."

 ch.runCommand(message, args, { proc ->
   proc.out.close() // close stdin
   proc.consumeProcessErrorStream(System.out) // forward stderr
   result = proc.text.trim();
 })

 println "[ok] Command returned " + result

 // extract the config file from the returned message
 startIndex = result.indexOf("export KUBECONFIG=") + 18;
 if (startIndex == -1) {
   throw new Exception("Could not find the string 'export KUBECONFIG=' in the returned message " + result);
 }
 endIndex = result.lastIndexOf(".yml") + 4;
 if (endIndex == -1) {
   throw new Exception("Could not find the string '.yml' in the returned message " + result);
 }
 configFile = result.substring(startIndex, endIndex);

 println "[action] Setting output property named kubeconfig to value " + configFile

 // Set the current-context as an output property
 apTool.setOutputProperty("kubeconfig", configFile);
 apTool.setOutputProperties();

