# V. Sadilovskiy on 06/11/2003
#
# This utility runs all or specified through a parameter healing script(s) for
# Intralink schema. The respective reports are created with the same name with extension .lst
#
# Required environment variables and parameters:
# PROI_HOME       - environment variable that specifies Pro/INTRALINK DS home folder
# ORA_SYS_PWD     - environment variable that specifies system's schema password
# <parameter(s)>  - list of the healing script name(s)
#

#########################################################################
#  Procedure:
#      Sqlplus - run SQL*Plus with connection by $UserPwd and executes
#                   all commands in $CmdTxt.
#
#  Input parameters:
#      UserPwd - "username/password"
#      CmdTxt  - commands to execute
#
#  Returned Value:
#      Return SQL*Plus output.
#
proc SqlPlusDbaRmt {CmdTxt} {
    global db_props errorCode ilnk_platform

    set ProcName SqlPlusDbaRmt
    DebugOutput "Procedure SqlPlusDbaRmt (RunSqlplus wrapper) started."

    catch {RunSqlplus "$db_props(SystemConnectStr)" $CmdTxt} sql_out
    return $sql_out
}

proc runHealingScripts {pdm_schema_user {healingScriptList ""}} {
    global db_props env

    set ::PatchHome $env(PROI_HOME)/dbs/ilink_patches
	cd $::PatchHome
	set ::PatchHome [file native "./"]
	set Healing_PATH  "./hl_scripts"
	if { [info exists env(PROI_INHOUSE_INSTALL)] } {
		set ReportDir "$env(TEMP)/patch_log"
	} else {
		#set ReportDir "./log"
		set ReportDir "$env(PROI_HOME)/dbs/ilink_patches/log"
	}
	if {[file exists ${ReportDir}] != 1} {
	   file mkdir ${ReportDir}
	}

	# Opening PDM account
    BeginSchemaUpdate

    # following for inhouse only
    if {[info exists env(PROI_INHOUSE_INSTALL)] && $env(PROI_INHOUSE_INSTALL) == "developer"} {
        set SqlCmd "
        alter user $pdm_schema_user account unlock;

    "
        set sql_tmp_out [SqlPlusDbaRmt ${SqlCmd}]
        DebugOutput "sql_out : ${sql_tmp_out}" 2

        set err_rep [OraErrorReport $sql_tmp_out ""]

        if {$err_rep != ""} {
            set ErrMsg "\nError during running sqlplus:"
            WriteErrorLog "$ErrMsg\n\n${err_rep}\n$sql_tmp_out"
            return -code "error" "createMigraitonSchema: $ErrMsg"
        }
    }
    # end of inhouse part

	WriteStdAndLog "Current directory: [file native [pwd]]\n"
    if {$healingScriptList == ""} {
    	        # Run all healing scripts
		Healing_Patches
		### SPR fixes: #1169814, #1250615. Use hl_famtab.sql from Data Migrator install	###
		### instead of Pro/I data server location. The sql file on Pro/I DS is very old ###
		### and does not handle nested FTs'correctly.                         		###
		#Healing_ONE "[file native ${Healing_PATH}/hl_famtab.sql] % % %" [file native "${ReportDir}/hl_famtab.lst"]
		cd $::MIG_PWD
		WriteStdAndLog "Current directory: [file native [pwd]]\n"
		Healing_ONE "[file native "./hl_famtab.sql"] % % %" [file native "${ReportDir}/hl_famtab.lst"]
		cd $::ilnk_platform(DatabaseDir)
	} else {
		foreach healingScript $healingScriptList {
			regsub -nocase ".sql" $healingScript "" healingScript
			if {$healingScript == "hl_famtab"} {
				cd $::MIG_PWD
				WriteStdAndLog "Current directory: [file native [pwd]]\n"
				Healing_ONE "[file native "./hl_famtab.sql"] % % %" [file native "${ReportDir}/hl_famtab.lst"]
				cd $::ilnk_platform(DatabaseDir)
			} else {
				Healing_ONE [file native ${Healing_PATH}/$healingScript].sql [file native "${ReportDir}/$healingScript"].lst
			}
		}
	}

	# Closing PDM account
    EndSchemaUpdate
}

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") && $argc == 1} {
#    set mig_schema_name $db_props(PdmUser)_migration
#    set mig_schema_pass [lindex $argv 0]
#} elseif {$argc == 2  && [info exists env(PROI_INHOUSE_INSTALL)] && $env(PROI_INHOUSE_INSTALL) == "developer"} {
#    set mig_schema_name [lindex $argv 0]
#    set mig_schema_pass [lindex $argv 1]
#} else {
#    puts "Incorrect parameter number."
#    return
#}

if {![info exists db_props(SystemConnectStr)] && ![info exists env(ORA_SYS_PWD)]} {
    puts "Please, set ORA_SYS_PWD environment variable."
    return
} elseif {![info exists db_props(SystemConnectStr)]} {
    set db_props(SystemConnectStr) "system/$env(ORA_SYS_PWD)@$db_props(ServiceName)"
}

if {[file pathtype [info script]] == "absolute"} {
    set scriptPath [file dirname [info script]]
} else {
    set scriptPath [file dirname "[pwd]/[info script]"]
}

SetupLogs "EPM Migration Doctor." UPDATE
set LogFile "$ilnk_platform(LogDir)${PathDlmtr}epm_migration_doctor.log"
if {![catch {package require ProILogger}]} {
	ProILogger::addLogFile "$LogFile" "details" "append"
	ProILogger::setLogTiming "$LogFile" "TRUE"
}
WriteStdAndLog "\n####################################################################################################\n"
WriteStdAndLog "Healing Pro/I before migration. Log file located at: [file native $LogFile]\n"
WriteStdAndLog "\n####################################################################################################\n"

set MIG_PWD [file native [pwd]]
cd $ilnk_platform(DatabaseDir)


# 2. populate synonyms to point to required tables in ${PDM_USER} schema
runHealingScripts $db_props(PdmUser) $argv

