# V. Sadilovskiy on 08/19/2004
#
# This wrapper utility runs provided sql script in PDM schema. Script is expected
# to locate in current folder.
#
# Required environment variables and parameters:
# PROI_HOME       - environment variable that specifies Pro/INTRALINK DS home folder
# PROI_SYS_PWD    - environment variable that specifies system's schema password
# PDM_ORACLE_SERVER - optional, denotes oracle service name of the dataserver
#

if {![info exists env(TCL_AUTO_PATH)]} {
    puts "Please, set TCL_AUTO_PATH environment variable properly."
    return
}

lappend auto_path $env(TCL_AUTO_PATH)
ilnk_init 1
lappend auto_path "$ilnk_platform(DatabaseDir)${PathDlmtr}Tcl"

if {![info exists env(PROI_INHOUSE_INSTALL)] && ![info exists env(PROI_SYS_PWD)]} {
    puts "Please, set PROI_SYS_PWD environment variable."
    return
} elseif {[info exists env(PROI_SYS_PWD)]} {
    set ProiPasswd $env(PROI_SYS_PWD)
}

if {(![info exists env(PROI_INHOUSE_INSTALL)] || $env(PROI_INHOUSE_INSTALL) == "customer" || $env(PROI_INHOUSE_INSTALL) == "developer") && $argc == 1} {
    set sql_script [lindex $argv 0]
} else {
    puts "Incorrect parameter number."
    return
}

SetupLogs "EPM Migration Installation." UPDATE
set LogFile "$ilnk_platform(LogDir)${PathDlmtr}epm_migration_schema.log"
if {![catch {package require ProILogger}]} {
	ProILogger::addLogFile "$LogFile" "details" "append"
	ProILogger::setLogTiming "$LogFile" "TRUE"
}

WriteStdAndLog "\n##########################################################################\n"
WriteStdAndLog "Running pdm_sql_wrapper. Log file located at: $LogFile"
WriteStdAndLog "\n##########################################################################\n"

# 1. Opening PDM account to grant select privileges
BeginSchemaUpdate

# 2. Running desired script
WriteStdAndLog "Running SQL script $sql_script ... "
set sql_cmd "
@${sql_script}
"
set sql_out [RunSqlplus $db_props(PdmConnectStr) "@${sql_script}" ]
DebugOutput "sql_out : ${sql_out}" 2

set err_rep [OraErrorReport $sql_out ""]

if {$err_rep != ""} {
    set ErrMsg "\nError during running sqlplus:"
    WriteErrorLog "$ErrMsg\n\n${err_rep}\n$sql_out"
    # return -code "error" "PDM sql wrapper: $ErrMsg"
} else {
    WriteStdAndLog "OK\n"
}

# 3. Closing PDM account
EndSchemaUpdate
