/*
* 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 java.nio.charset.Charset

import com.urbancode.air.AirPluginTool

AirPluginTool airTool = new AirPluginTool(args[0], args[1])
Properties props = airTool.getStepProperties()
def workDir = new File('.').canonicalFile

def fileName = props['file']
def overwrite = props['overwrite']?.toBoolean()
def contents = props['contents']?:''
def encoding = props['encoding']?:''
String customEncoding = props['customEncoding']?.trim()

try {
    Charset encodingToUse = null;
    Charset defaultEncoding = Charset.forName(System.getenv("DS_SYSTEM_ENCODING"));
    if (customEncoding) {
        encodingToUse = Charset.forName(customEncoding);
    } else {
        encodingToUse = defaultEncoding;
    }

    File file = new File(fileName).getCanonicalFile();
    if (file.exists() && !overwrite) {
        println "File $file already exists!"
        System.exit 1
    }
    else {
        println "Using file encoding " + encodingToUse.name()

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), encodingToUse);
        outputStreamWriter.write(contents)
        outputStreamWriter.close()

        println "Successfully ${overwrite ? 'replaced' : 'created'} file $file"
        if (encodingToUse.equals(defaultEncoding)) {
            println "Wrote the following contents to the file:"
            println contents
        } else {
            println "Wrote the contents to the file. Cannot preview written contents because system encoding and the specified custom file encoding differ."
        }
    }
}
catch (Exception e) {
    println "Error creating file $fileName: ${e.message}"
    System.exit(1)
}

System.exit(0)
