#!/usr/bin/env groovy
import java.util.Arrays
import java.util.stream.Collectors

def stageDir = new File(this.args[0]);
def propFile = new String(this.args[0]+"/vendor.properties");
def exts = [".xml"]

rebrandFiles(propFile, stageDir, exts);

def log(msg) {
    if (!!msg?.trim()) {
        println(msg)
    }
}

def rebrandFiles(String propFile, File stageDir, ArrayList exts) {
    log("property file = "+propFile);
    log("stageDir = "+stageDir);
    Properties props = new Properties()
    File propsFile = new File(propFile)
    propsFile.withInputStream {
        props.load it
    }
    Set<Object> keys = props.keySet();
    for (String key : keys) {
        String value = props.get(key)
        println("stageDir = " + stageDir);
        stageDir.eachFileRecurse(
            { file ->
                for (ext in exts) {
                    if (file.name.endsWith(ext)) {
                        log("Re-branding in-progress for " + file.name);
                        fileText = file.text;
                        fileText = fileText.replaceAll(key, value)
                        file.write(fileText);
                        log("Re-branding complete for " + file.name);
                    }
                }
            }
        )
    }
}
