/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

final def fromDir = props['sourceDir']
final def toDirs = props['destDirList']
final def includes = props['includes']
final def excludes = props['excludes']
final def overwriteFlag = Boolean.valueOf(props['overwrite']?.trim()?:false);
final def preserveInTargetIncludes = props['preserveInTargetIncludes'];
final def preserveInTargetExcludes = props['preserveInTargetExcludes'];

if (!fromDir) { fromDir = workDir.canonicalPath }

def ant = new AntBuilder()
try {
    toDirs.eachLine {toDir ->
        ant.echo("Preparing to synchronize " + fromDir + " with " + toDir)
        ant.sync(verbose: "true", todir: toDir, overwrite:overwriteFlag) {
            fileset(dir: fromDir) {
                includes.eachLine { includeRule ->
                    include(name: includeRule)
                }
                excludes?.eachLine { excludeRule ->
                    exclude(name: excludeRule)
                }
            }
            if (preserveInTargetIncludes?.trim() || preserveInTargetExcludes?.trim()) {
                preserveintarget() {
                    preserveInTargetIncludes.eachLine { preserveRule ->
                        include(name: preserveRule)
                    }
                    preserveInTargetExcludes.eachLine { preserveRule ->
                        exclude(name: preserveRule)
                    }
                }
            }
        }
    }
}
catch (Exception e) {
    println "Error synchronizing directories: ${e.message}"
    System.exit(1)
}

System.exit(0)

