#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 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.ud.client.PropertyClient
import com.urbancode.ud.client.ComponentClient
import com.urbancode.commons.fileutils.FileUtils
import com.urbancode.commons.fileutils.DirectoryFileFilter

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 weburl = System.getenv("AH_WEB_URL")

def includes = props['includes']
def excludes = props['excludes']
def deleteExtraProps = props['deleteExtraProps'].toBoolean()
def username = apTool.getAuthTokenUsername()
def password = apTool.getAuthToken()

try {
    def componentClient = new ComponentClient(new URI(weburl), username, password)
    def propertyClient = new PropertyClient(new URI(weburl), username, password);

    def fileFilter = DirectoryFileFilter.getFilter(new File("."), true);
    fileFilter.addIncludes(includes.split("/n"));
    fileFilter.addExcludes(excludes.split("/n"));
    def files = FileUtils.getFilesRecursively(new File("."), fileFilter);

    files.each() { propFile ->

        def propsStream = new FileInputStream(propFile)

        Properties properties = new Properties()
        properties.load(propsStream)
        propsStream.close();
        Properties templateProperties = new Properties()

        def componentName = properties.getProperty("ComponentName").toString();
        def componentId = componentClient.getComponentUUID(componentName);

        def propSheetDefPath = "components/"+componentId.toString()+"/environmentPropSheetDef"

        JSONArray propDefJson = new JSONArray();
        Properties onlyWantedProps =new Properties();
        properties.propertyNames().each() { propName ->
            if (!propName.equals("ComponentName")) {
                onlyWantedProps.setProperty(propName, properties.getProperty(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);
            }
        }
        properties = onlyWantedProps;

        println "Outputing Property Changes for Component " + componentName;
        def oldPropertiesArray = propertyClient.getPropSheetDefPropDefs(propSheetDefPath);
        propertyHelper.outputPropertyChanges(properties, oldPropertiesArray, deleteExtraProps);
        println "\n"

        propertyClient.updatePropDefs(propSheetDefPath, propDefJson, deleteExtraProps);

        def outStream  = new FileOutputStream(propFile, false)
        templateProperties.store(outStream, "properties for component: " + componentName);
        outStream.close();
    }
} catch (Exception e) {
    println "Error Updating Properties!";
    e.printStackTrace()
    System.exit(1)
}
