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

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

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

def fromDir = props['sourceDir']
def toDirs = props['destDirList']
def includes = props['includes']
def excludes = props['excludes']
def overwriteFlag = Boolean.valueOf(props['overwrite']?.trim()?:false);
def preserveInTargetIncludes = props['preserveInTargetIncludes'];
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)
