/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 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

final AirPluginTool airTool = new AirPluginTool(args[0], args[1])
final Properties props = airTool.getStepProperties()

final def workDir = new File('.').canonicalFile

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)
