/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2014. 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

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

final def fileName = props['file']
final def overwrite = props['overwrite']?.toBoolean()
final def contents = props['contents']?:''
final 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)
