#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2015. 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.ud.client.ResourceClient;
import com.urbancode.ud.client.PropertyClient;

import propertyHelper;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();

def propFileName = props['propFile'];
def resourceName = props['resource'];
def username = apTool.getAuthTokenUsername();
def password = apTool.getAuthToken();
Properties properties = new Properties();

def propFile = new File(propFileName);
def propsStream = null;

try {
    propsStream = new FileInputStream(propFile);
    properties.load(propsStream);
    propsStream.close();

    def weburl = System.getenv("AH_WEB_URL");
    def resourceClient = new ResourceClient(new URI(weburl), username, password);
    def propertyClient = new PropertyClient(new URI(weburl), username, password);

    JSONObject propDefJson = new JSONObject();
    StringBuilder sb = new StringBuilder();
    properties.propertyNames().each() { propName ->
	sb.append(propName);
	sb.append("=");
	sb.append(properties.getProperty(propName));
        sb.append("\n");
    }
    propDefJson.put("properties", sb.toString());

    JSONObject resourceInfo = resourceClient.getResourceByPath(resourceName);
    if (resourceInfo && resourceInfo.has("propSheet")) {
        JSONObject propSheet = resourceInfo.getJSONObject("propSheet");
        propertyClient.updateResourcePropValues(propSheet.getString("path"), propSheet.getString("version"), propDefJson);
    }
    else {
        println "Failed to find resource info for $resourceName!";
        e.printStackTrace();
        System.exit(1);
    }

} catch (Exception e) {
    println "Error Updating Properties!";
    e.printStackTrace();
    System.exit(1);
}
