/*
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Deploy
 * (c) Copyright IBM Corporation 2002, 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.util.regex.Pattern
import java.util.regex.Matcher

import org.apache.commons.io.filefilter.WildcardFileFilter
import org.apache.commons.io.comparator.NameFileComparator

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugins.sqlplus.SQLPlusHelper

final AirPluginTool airPluginTool = new AirPluginTool(args[0], args[1])

final Properties props = airPluginTool.getStepProperties()

// Gather Properties
def AGENT_HOME = new File(System.getenv("AGENT_HOME").toString() + File.separator + "var" + File.separator + "temp")
def separator = '\n|[\n]|\r\n|[\r\n]'
def sqlPlusExecutable = props['sqlPlusExecutable']
println "Executable : " + sqlPlusExecutable
def user = props['user'].trim()
println "User : ${user.trim()?:'Oracle Wallet'}"
final def passScript = props['passScript']
def password = props['password']
def connectionID = props['connectionID']
println "ConnectionID : " + connectionID
def unparsedSqlFiles = props['sqlFiles']
unparsedSqlFiles = unparsedSqlFiles.replaceAll(separator, ",")
def sqlFiles = unparsedSqlFiles.tokenize(',')
def unparsedSqlFilesArgs = props['sqlFileArgs']
unparsedSqlFilesArgs = unparsedSqlFilesArgs.replaceAll(separator, ",")
def sqlFileArgs = unparsedSqlFilesArgs.split(',')*.trim()
def failOnORA = props['failOnORA']?.toBoolean()
def skipSqlErrors = props['skipSqlErrors'] ? props['skipSqlErrors'].toBoolean() : false
def oracleHome = props['oracleHome']

def unparsedEnvVars = props['additionalEnvVars']
unparsedEnvVars = unparsedEnvVars.replace(separator, ",").split(',')
def envVars = unparsedEnvVars*.trim()
envVars.removeAll([""])

println "SQL Files : "
sqlFiles.each { println "\t" + it }

println "SQL Files Args : "
sqlFileArgs.each { println "\t" + it }

ListIterator<String> sqlArgsIterator = sqlFileArgs.listIterator()
SQLPlusHelper sqlHelper = new SQLPlusHelper(user, password, passScript, oracleHome, connectionID)
sqlFiles = sqlHelper.getExistingScripts(sqlFiles)

if (envVars && envVars.size() > 0) {
    sqlHelper.validateEnvVars(envVars)
}

if (!skipSqlErrors) {
    sqlFiles = sqlHelper.getScriptsWithErrorHandling(sqlFiles)
    sqlFiles.each { sqlFileName ->
        String output = sqlHelper.runSQLFile(sqlPlusExecutable, sqlFileName, sqlArgsIterator, envVars)
        sqlHelper.checkOutputForErrors(output, failOnORA)
    }
}
else {
    println("[Warn] Skipping any PLS, SP2, or ORA errors during SQL script execution.")
    sqlFiles.each { sqlFileName ->
        sqlHelper.runSQLFile(sqlPlusExecutable, sqlFileName, sqlArgsIterator, envVars)
    }
}





