/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2018. 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 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()

    // Confirm file(s) exist from given zipFile input
    def scanner = ant.fileScanner {
      fileset(dir:'.', includes:zipFile, casesensitive:'false')
    }
    if (!scanner.iterator().hasNext()) {
        throw new FileNotFoundException("[error] Could not find .zip file(s) from '${zipFile}' input.")
    }

    // Unzip the files
    ant.project.getBuildListeners().firstElement().setMessageOutputLevel(3)
    ant.unzip(
        dest:dirOffset,
        failOnEmptyArchive: 'true',
        overwrite: overwrite,
        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)
