/*
* 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

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,
            includeEmptyDirs: "true")
        {
            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)
