/*
* 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 dirOffset = props['dir']?:'.'
def tarball = props['tarball'];
def compression = props['compression'];
def overwrite = Boolean.valueOf(props['overwrite']);

def overwrite_str = 'false'
if (overwrite){
    overwrite_str = 'true'
}

try {

    def ant = new AntBuilder()
    def fileDir ="."
    def tarballfile =new File(tarball)
    if(tarballfile.parent) {
        fileDir= tarballfile.parentFile.canonicalPath
    }

    def scanner = ant.fileScanner {
        fileset(dir: fileDir ) {
            include(name: tarballfile.name);
        }
    }

    // if the fileScanner has no matches, exit
    if (!scanner.hasFiles()) {
        println "[Error] File '${tarballfile.canonicalPath}' not found."
        System.exit(1)
    }

    // if we find a directory, exit
    if(scanner.directories().size() > 0) {
        println "[Error] '${tarballfile.canonicalPath}' is a directory, or a pattern that returns a directory."
        System.exit(1)
    }

    println "File directory is: ${fileDir}"

    ant.untar(
            dest:dirOffset,
            failOnEmptyArchive: 'true',
            compression: compression,
            overwrite: overwrite_str,
            encoding: "UTF-8") {
                fileset(dir:fileDir, includes:tarballfile.name)
            }
}
catch (Exception e) {
    e.printStackTrace()
    println "Error extracting tarball!"
    System.exit(1)
}
finally {
}

System.exit(0)
