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)

