/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import java.nio.charset.Charset
import com.urbancode.air.AirPluginTool

AirPluginTool airTool = new AirPluginTool(args[0], args[1])
Properties inProps = airTool.getStepProperties()
def dirOffset = inProps['dir']?:'.'
def zipFile = inProps['zip'];
def overwrite = Boolean.valueOf(inProps['overwrite']);
def includes = inProps['includes'];
def excludes = inProps['excludes'];
def customEncoding = inProps['customEncoding']

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

def encoding
if (customEncoding) {
    try {
        encodingSupported = Charset.isSupported(customEncoding)
    }
    catch (IllegalArgumentException iae) {
        println ("[error]  Encoding type ${customEncoding} not valid.")
        println ('[possible solution]  Please update the step configuration with a valid encoding type.')
        System.exit(1)
    }
    if (!encodingSupported) {
        println ("[error]  Encoding type ${customEncoding} not supported.")
        println ('[possible solution]  Please update the step configuration with a supported encoding type.')
        System.exit(1)
    }
    else {
        encoding = customEncoding
    }
}
else {
    File AGENT_HOME;
    if (System.getenv().get("AGENT_HOME")){
        AGENT_HOME = new File(System.getenv().get("AGENT_HOME"))
    }
    if (AGENT_HOME) {
        final def agentInstalledProps = new File(AGENT_HOME, "conf/agent/installed.properties")
        final def agentProps = new Properties();
        final def agentInputStream = null;
        try {
            agentInputStream = new FileInputStream(agentInstalledProps);
            agentProps.load(agentInputStream);
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        encoding = agentProps['system.default.encoding']
    }
}

try {

    def ant = new AntBuilder()
    if (overwrite) {
        ant.unzip(
                dest:dirOffset,
                failOnEmptyArchive: 'true',
                overwrite: 'true',
                encoding: encoding) {
            fileset(dir:'.', includes:zipFile, casesensitive:'false')
            patternset(includes: includes, excludes: excludes)
        }
    }
    else {
        ant.unzip(
                dest:dirOffset,
                failOnEmptyArchive: 'true',
                overwrite: 'false',
                encoding: encoding) {
            fileset(dir:'.', includes:zipFile, casesensitive:'false')
            patternset(includes: includes, excludes: excludes)
        }
    }
}
catch (Exception e) {
    e.printStackTrace()
    println "[error]  Could not complete unzip successfully."
    System.exit(1)
}
finally {
}

System.exit(0)

