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

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 componentName = props['component']
def deleteExtraProps = props['deleteExtraProps'].toBoolean()
def outputFileName = props['outputFile']
def username = apTool.getAuthTokenUsername()
def password = apTool.getAuthToken()

Properties properties = new Properties()
Properties templateProperties = new Properties()

def propFile = new File(propFileName)
def outputFile = new File(outputFileName)
def outStream = null;
def propsStream = null;

try {
    outStream = new FileOutputStream(outputFile)
    propsStream = new FileInputStream(propFile)
    properties.load(propsStream)
    propsStream.close();
    
    def weburl = System.getenv("AH_WEB_URL")
    def componentClient = new ComponentClient(new URI(weburl), username, password)
    def propertyClient = new PropertyClient(new URI(weburl), username, password);
    def componentId = componentClient.getComponentUUID(componentName);
    
    def propSheetDefPath = "components/"+componentId.toString()+"/environmentPropSheetDef.-1"
    
    JSONArray propDefJson = new JSONArray();
    properties.propertyNames().each() { propName ->
        def propValue = properties.getProperty(propName)
        templateProperties.setProperty(propName, "@"+propName+"@");
        JSONObject entry = new JSONObject();
        entry.put("name", propName);
        entry.put("value", propValue);
        propDefJson.put(entry);
    }
    
    def oldPropertiesArray = propertyClient.getPropSheetDefPropDefs(propSheetDefPath);
    propertyHelper.outputPropertyChanges(properties, oldPropertiesArray, deleteExtraProps);
    
    propertyClient.updatePropDefs(propSheetDefPath, propDefJson, deleteExtraProps);
    
    templateProperties.store(outStream, "properties for component: " + componentName);
    outStream.close();
} catch (Exception e) {
    println "Error Updating Properties!";
    e.printStackTrace()
    System.exit(1)
}
