#!/bin/bash
# IBM Confidential
# OCO Source Materials
# 5724-V51
#
# (c) Copyright IBM Corp. 2000, 2008 All Rights Reserved.
#
# The source code for this program is not published or otherwise
# divested of its trade secrets, irrespective of what has been
# deposited with the U.S. Copyright Office.
# 
# # Copyright (c) 2000, 2004 IBM Corp. - All Rights Reserved.
# # IBM makes no representations or warranties about the suitability of
# # this program, either express or implied, including but not limited to
# # the implied warranties of merchantability, fitness for a particular
# # purpose, or non-infringement. 
# 
#


# The purpose of this script is to migrate the database schema from 5.3.2.16 to 6.0.0.6
# Please consult InfoSphere MDM Server for PIM Support before attempting to use this script


if [ -z "$TOP" -o ! -r "$TOP" ]; then
   ${ECHO} TOP variable not defined
   exit 1
fi

# Set the 5.3.2-FP0016 database to be migrated to 6.0.0-FP006

${ECHO}
${ECHO} "********************************************************"
${ECHO} "********************************************************"
${ECHO} "**"
${ECHO} COMMON_INFO_MIGRATE_SCHEMA_SH
${ECHO} COMMON_INFO_BACKUP_DB_WARNING_SH
${ECHO} "**"
${ECHO} "********************************************************"
${ECHO} "********************************************************"
${ECHO}

. ${TOP}/src/db/schema/util/set_db_localized.sh "$@"
_ERROR_LOGS=$TOP/logs/errfile.log
${ECHO} " " > $_ERROR_LOGS

GET_COMPANIES=`. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_CMN_SCRIPTS/get_cmpcode.sql`
COMPANIES="${GET_COMPANIES}"
`rm -f $DB_SCRIPTS/verifyFPMigration.sql `

EXISTS=1;
NOTEXISTS=0;
count=0;

if [ -d $TOP/tmp ]; then
  TMPDIREXISTS=$EXISTS
else
  TMPDIREXISTS=$NOTEXISTS
fi




getErrorCountInLogFile()
{
    if [ ! -f $_ERROR_LOGS ]; then
        errorCount=0
    else
        errorCount=`cat $_ERROR_LOGS | wc -c`
    fi
}

DoStartAndPrepare()
{
    ${ECHO} 
    ${ECHO} $1
    ${ECHO} 

    getErrorCountInLogFile
    initial=$errorCount
}

DoEndAndReportError()
{

    getErrorCountInLogFile
    final=$errorCount

    if [ ! $initial -eq $final ]; then

        ${ECHO} "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        ${ECHO} $1
        ${ECHO} "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
        ${ECHO} "COMMON_INFO_CHECK_ERROR_LOG_FILE_SH" $_ERROR_LOGS
        
    else
    	${ECHO} ""
        ${ECHO} "-----------------------------------------"
        ${ECHO} $2
        ${ECHO} "-----------------------------------------"
	fi

}



# Define the functions for schema changes

migrateNewTables()
{	
	DoStartAndPrepare "COMMON_INFO_UPDATING_SH New Tables"   
	  	
		. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/create_tss_tsd_aud_tables.sql --errorfilter=yes 2>> $_ERROR_LOGS
	
	if [ ${CCD_DB} = "oracle" ]; then
		${ECHO} "describe taud_alo_audit_log;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "describe tctg_tss_template_search_sort;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "describe tctg_tsd_template_search_data;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "describe tldr_dat_data_table;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "describe tldr_stt_status_table;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "column column_name format a30;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select index_name, column_name, column_position from user_ind_columns where table_name='TAUD_ALO_AUDIT_LOG' order by 1, 3;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select index_name, column_name, column_position from user_ind_columns where table_name='TCTG_TSS_TEMPLATE_SEARCH_SORT' order by 1, 3;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select index_name, column_name, column_position from user_ind_columns where table_name='TCTG_TSD_TEMPLATE_SEARCH_DATA' order by 1, 3;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		
	else
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TAUD_ALO_AUDIT_LOG' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TCTG_TSS_TEMPLATE_SEARCH_SORT' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TCTG_TSD_TEMPLATE_SEARCH_DATA' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TLDR_DAT_DATA_TABLE' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TLDR_STT_STATUS_TABLE' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select indname, colname, colseq from syscat.indexcoluse where indschema= CURRENT SCHEMA and indname='IAUD_ALO_0' order by indname, colseq;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select indname, colname, colseq from syscat.indexcoluse where indschema= CURRENT SCHEMA and indname='ICTG_TSS_0' order by indname, colseq;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
		${ECHO} "select indname, colname, colseq from syscat.indexcoluse where indschema= CURRENT SCHEMA and indname='ICTG_TSD_0' order by indname, colseq;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
	fi
		
	DoEndAndReportError  "COMMON_INFO_FAILED_SH New Tables" "COMMON_INFO_SUCCEEDED_SH New Tables"	
}


migrateAuditLogs()
{
	DoStartAndPrepare "COMMON_INFO_UPDATING_SH Audit Log Table"    
	 	
		. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_CMN_SCRIPTS/update_audit_log.sql --errorfilter=yes 2>> $_ERROR_LOGS | ${GREP} -v '.*'			
		
	DoEndAndReportError  "COMMON_INFO_FAILED_SH Audit Log Table" "COMMON_INFO_SUCCEEDED_SH Audit Log Table"
}


migrateAttributeGroup()
{
	DoStartAndPrepare "COMMON_INFO_UPDATING_SH Attribute Group"    
	 	
		. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/alter_atg_table.sql --errorfilter=yes 2>> $_ERROR_LOGS 
		
	if [ ${CCD_DB} = "oracle" ]; then
		${ECHO} "describe TCTG_ATG_ATTR_GROUP;" >> ${DB_SCRIPTS}/verifyFPMigration.sql		
	else
		${ECHO} "select COLNAME from syscat.columns where TABNAME = 'TCTG_ATG_ATTR_GROUP' AND TABSCHEMA = CURRENT SCHEMA;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
	fi
		
	DoEndAndReportError  "COMMON_INFO_FAILED_SH Attribute Group" "COMMON_INFO_SUCCEEDED_SH Attribute Group"
}


migrateSchemaSynchronization()
{
    DoStartAndPrepare "COMMON_INFO_UPDATING_SH Schema Synchronization"
    
        . ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/schemaSynchMigrate.sql --errorfilter=yes 2>> $_ERROR_LOGS| ${GREP} -v '.*'
        
        ${JAVA_RT} com.ibm.ccd.synchronize.DBSchemaVersion --autoupd 2>> $_ERROR_LOGS 
        
        ${ECHO} "select * from tsynch_dbv_schema;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
          
    DoEndAndReportError  "COMMON_INFO_FAILED_SH Schema Synchronization." "COMMON_INFO_SUCCEEDED_SH Schema Synchronization"
}


updateLkpTablePrivileges()
{
	DoStartAndPrepare "COMMON_INFO_UPDATING_SH LookupTable Privileges"
		for CMP_CODE_COL in $COMPANIES; 
		do
	        CMP_CODE=`${ECHO} ${CMP_CODE_COL} | ${GREP} 'cmpcode%' | ${CUT} -f2 -d "%"`         
	     	if [ "$CMP_CODE" != "" ]; then
				$JAVA_RT com.ibm.ccd.common.interpreter.test.TestScript --companycode=$CMP_CODE --scriptpath=$TOP/bin/updateLkpTableACGs.wpcs --username="Admin" 2>> $TOP/logs/errfile1.log				
			fi            
	    done 
	    `rm -f $TOP/logs/errfile1.log `
	DoEndAndReportError  "COMMON_INFO_FAILED_SH LookupTable Privileges" "COMMON_INFO_SUCCEEDED_SH LookupTable Privileges"
}

updateAuditLogs()
{
	DoStartAndPrepare "COMMON_INFO_UPDATING_SH Audit Logs"
	
		$JAVA_RT com.ibm.ccd.common.migration.AuditLogMigration 2>> $_ERROR_LOGS 
		
	DoEndAndReportError  "COMMON_INFO_FAILED_SH Audit Logs" "COMMON_INFO_SUCCEEDED_SH Audit Logs"	
}

migrateACG()
{
    DoStartAndPrepare "COMMON_INFO_UPDATING_SH ACG"
    
	    exportACGRoles
	    recreateObjectActions
	    importACGRoles    
	    updateAdminRoles
	    
    DoEndAndReportError  "COMMON_INFO_FAILED_SH ACG." "COMMON_INFO_SUCCEEDED_SH ACG"
}


exportACGRoles() 
{	
	for CMP_CODE_COL in $COMPANIES; 
	do
		CMP_CODE=`${ECHO} ${CMP_CODE_COL} | ${GREP} 'cmpcode%' | ${CUT} -f2 -d "%"`         
        if [ "$CMP_CODE" != "" ]; then        	
			${ECHO} "COMMON_INFO_EXPORTING_ACG_ROLES_SH" $CMP_CODE
			${ECHO} 
			
			$JAVA_RT com.ibm.ccd.envexpimp.common.EnvironmentExporter -companycode="$CMP_CODE" -scriptpath=$TOP/bin/exportACGRolesScript.wpcs 2>> $_ERROR_LOGS	
								
			$JAVA_RT com.ibm.ccd.docstore.util.DocDownloader -companycode="$CMP_CODE" -subtree=archives/fpmigration/ -xmlfile=$TOP/tmp/abc.xml -rootlocalpath=$TOP/tmp/ 2>> $_ERROR_LOGS | ${GREP} -v '.*'
			
			`mv $TOP/tmp/__archives__fpmigration__Export.zip $TOP/tmp/__archives__fpmigration__cmp"$count".zip `
		      	
			count=`expr $count + 1`
				
			`rm -f $TOP/tmp/abc.xml `
		fi            
	done
}

recreateObjectActions()
{
	. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_CMN_SCRIPTS/recreateOAC_OBT.sql --errorfilter=yes 2>> $_ERROR_LOGS | ${GREP} -v '.*'
	
	${ECHO} "select count(*) NO_OF_OAC_RECORDS from oac;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
	${ECHO} "select count(*) NO_OF_OBT_RECORDS from obt;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
}

importACGRoles()
{
	count=0;
	for CMP_CODE_COL in $COMPANIES; 
	do
        CMP_CODE=`${ECHO} ${CMP_CODE_COL} | ${GREP} 'cmpcode%' | ${CUT} -f2 -d "%"`         
     	if [ "$CMP_CODE" != "" ]; then
        	${ECHO} "COMMON_INFO_IMPORTING_ACG_ROLES_SH" $CMP_CODE
        	${ECHO}
        	$JAVA_RT com.ibm.ccd.envexpimp.common.EnvironmentImporter -companycode="$CMP_CODE" -zipfilepath=$TOP/tmp/__archives__fpmigration__cmp"$count".zip 2>> $_ERROR_LOGS | ${GREP} -v '.*'
        	            	
	      	if [ $TMPDIREXISTS -eq $EXISTS ]; then
	     		`rm $TOP/tmp/__archives__fpmigration__cmp"$count".zip `
	   		fi		
	   		
	   		count=`expr $count + 1`
        fi            
    done
	
	if [ $TMPDIREXISTS -eq $NOTEXISTS ]; then
   		`rm -rf $TOP/tmp/ `
	fi
}

updateAdminRoles()
{	
	`rm -f $DB_SCRIPTS/updateAdminORM.sql `
	${ECHO} " " > ${DB_SCRIPTS}/updateAdminORM.sql
	for CMP_CODE_COL in $COMPANIES; 
	do
        CMP_CODE=`${ECHO} ${CMP_CODE_COL} | ${GREP} 'cmpcode%' | ${CUT} -f2 -d "%"`         
     	if [ "$CMP_CODE" != "" ]; then    		
			${ECHO} "update orm set orm_access = 'feffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01'
					 where orm_company_id=(select cmp_company_id from cmp where cmp_company_code='$CMP_CODE') 
						and orm_role_id=(select rol_role_id from rol 
                  						 where rol_company_id=(select cmp_company_id from cmp where cmp_company_code='$CMP_CODE') 
                    						and rol_role_name like '%_admin');" >> ${DB_SCRIPTS}/updateAdminORM.sql
     	fi            
    done  
    . ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/updateAdminORM.sql --errorfilter=yes 2>> $_ERROR_LOGS 
}

updateITACABColumns()
{
    DoStartAndPrepare "COMMON_INFO_UPDATING_SH ITA_CAB_Columns"
        . ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/alter_ita_cab_columns.sql --errorfilter=yes 2>> $_ERROR_LOGS
    DoEndAndReportError  "COMMON_INFO_FAILED_SH ITA_CAB_Columns" "COMMON_INFO_SUCCEEDED_SH ITA_CAB_Columns"
    ${ECHO} "describe ita;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
    ${ECHO} "describe cab;" >> ${DB_SCRIPTS}/verifyFPMigration.sql
}



# Call the functions to make changes in the schema

migrateSchemaSynchronization
migrateACG
migrateNewTables
migrateAuditLogs
updateAuditLogs
migrateAttributeGroup
updateLkpTablePrivileges
updateITACABColumns



#
# Verification step
#

`rm -f $TOP/logs/verify.log ` 
. ${DB_DIR}/util/run_db_cmd.sh --file=$DB_SCRIPTS/verifyFPMigration.sql --errorfilter=yes >> $TOP/logs/verify.log




