/*
* 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 toDir = props['destDir']
final def includes = props['includes']
final def excludes = props['excludes']
final def mapperRules = props['mapperRules'];

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

def noFilter = includes?.trim()?.equals("**/*") && excludes?.trim()?.equals("")

def ant = new AntBuilder()
try {
    ant.echo("Preparing Move from " + fromDir + " to " + toDir)
    ant.move(verbose: "true", todir: toDir, overwrite: "true") {
        fileset(dir: fromDir) {
            if (!noFilter) {
                includes.eachLine { includeRule ->
                    include(name: includeRule)
                }
                excludes?.eachLine { excludeRule ->
                    exclude(name: excludeRule)
                }
            }
        }
        if(mapperRules) {
            compositemapper() {
                mapperRules.eachLine { mapRule ->
                    def rules = mapRule.split("->", 2);
                    if(rules.length != 2) {
                        throw new IllegalArgumentException('The mapper rule "' + mapRule + '" is not valid.');
                    }

                    for(int i = 0; i < rules.length; i++) {
                        if(rules[i].count("*") > 1) {
                            throw new IllegalArgumentException('The mapping rule "' + rules[i] + '" cannot contain more than one *.');
                        }
                    }
                    globmapper(from: rules[0].trim(), to: rules[1].trim());
                }
                globmapper(from: "*", to: "*");
            }
        }
    }
}
catch (Exception e) {
    println "Error moving directory: ${e.message}"
    System.exit(1)
}

System.exit(0)
