#!/bin/bash

set +x

CURR_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
cd "${CURR_PATH}" || exit 1
xmlFile=/home/ICUser/RDInstalled.xml
BCM_PATH=``
if [ -f "${xmlFile}" ]; then
    BCM_PATH=$(cat $xmlFile  | grep installpath | awk -F "\"" '{print $2}')
fi

PLUGINS_PATH="$BCM_PATH/Runtime/LegoRuntime/plugins"
BIN_PATH="$BCM_PATH/Runtime/bin"
RUNTIME_PATH="$BCM_PATH/Runtime"
TOMCAT_PATH="$BCM_PATH/Runtime/Tomcat6"
NODEAGENT_PATH="$BCM_PATH/Runtime/NodeAgent"
LOGDIR="$CURR_PATH/log"
CONFDIR="$BCM_PATH/Runtime/LegoRuntime/conf"


installStatus="false"
isBackup="false"
rollbackStatus="false"
gaussDbStatus=""

# 8.5.0.SPC200 jars
baseJar=${PLUGINS_PATH}/DRM-Base-Bundle-0.0.1-SNAPSHOT.jar
kubernetesJar=${PLUGINS_PATH}/DRM-Kubernetes-Manager-Bundle-0.0.1-SNAPSHOT.jar
storageCommonJar=${PLUGINS_PATH}/DRM-Storage-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
oracleJar=${PLUGINS_PATH}/DRM-Oracle-Manager-Bundle-0.0.1-SNAPSHOT.jar
databaseJar=${PLUGINS_PATH}/DRM-Database-Base-Bundle-0.0.1-SNAPSHOT.jar
CDRJar=${PLUGINS_PATH}/DRM-HW-CDR-Bundle-0.0.1-SNAPSHOT.jar
rdBaseJar=${TOMCAT_PATH}/Lego-UI-Plat/WEB-INF/lib/rd_base.jar
coreSdkJar=${PLUGINS_PATH}/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
storageJar=${PLUGINS_PATH}/DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar
commonJar=${PLUGINS_PATH}/DRM-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
hostJar=${PLUGINS_PATH}/DRM-Host-Bundle-0.0.1-SNAPSHOT.jar
coreCommonJar=${PLUGINS_PATH}/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
vsphereJar=${PLUGINS_PATH}/DRM-vSphere-Bundle-0.0.1-SNAPSHOT.jar
legoCoreBaseCommonJar=${PLUGINS_PATH}/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
ubaseCoreSDKCommon=${PLUGINS_PATH}/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
ubaseCoreSDKCommonTomcat=${TOMCAT_PATH}/Lego-UI-Plat/WEB-INF/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
ubaseCoreSDKCommonNodeAgent=${NODEAGENT_PATH}/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
hwHvsSraJar=${PLUGINS_PATH}/DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar
i18nFrontJar=${PLUGINS_PATH}/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar
i18nBackendJar=${TOMCAT_PATH}/Lego-UI-Plat/WEB-INF/lib/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar
fusionsphereJar=${TOMCAT_PATH}/Lego-UI-Plat/WEB-INF/lib/fusionsphere.jar

legoPropertiesFile="${CONFDIR}/lego.properties"
backupRecord="${CURR_PATH}/backupPath/record.properties"
patchVersionFile="${RUNTIME_PATH}/patch/package/patchVersion.conf"

if ! [ -d $LOGDIR ];then mkdir $LOGDIR ;fi
logfile="$LOGDIR/log_$(date +"%Y-%m-%d").log"

function log() {
    now_time='['$(date +"%Y-%m-%d %H:%M:%S")']'
    echo -e $1
    echo ${now_time} $1 >> ${logfile}
}

function setUserEnv() {
    # DRManager
    MAINTENANCE_USER=$(cat $BIN_PATH/config/conf/startInfo.properties | grep -v '^#' | grep maintenance.user.name |awk -F = '{print $2}'| tr -d '\r\n')
    # OMUser
    OM_USER_NAME=$(cat $BIN_PATH/config/conf/startInfo.properties | grep -v '^#' | grep custom.om.user.name | awk -F = '{print $2}'| tr -d '\r\n')
    # ICUser
    SYS_USER_NAME=$(cat $BIN_PATH/config/conf/startInfo.properties | grep -v '^#' | grep custom.user.name | awk -F = '{print $2}'| tr -d '\r\n')
    log "Start to set user env for $MAINTENANCE_USER, $OM_USER_NAME, $SYS_USER_NAME."
    addUserEnv "$SYS_USER_NAME"
    addUserEnv "$MAINTENANCE_USER"
    addUserEnv "$OM_USER_NAME"
    log "Set User env successfully."
}

function addUserEnv() {
    local -r userName=$1
    grep -i "export PATH" "/home/$userName/.bashrc" &>/dev/null
    if [ $? != 0 ];then
        echo "export PATH=/usr/sbin:$PATH" >> "/home/$userName/.bashrc" 2>/dev/null
    fi

    grep -i "umask 027" "/home/$userName/.bashrc" &>/dev/null
    if [ $? != 0 ];then
        echo "umask 027" >> "/home/$userName/.bashrc" 2>/dev/null
    fi
}

function backUpPatchVersion() {
    log "Begin to back up patch version file..."

    if [ ! -d "${RUNTIME_PATH}"/patch/package ]; then
        mkdir -p "${RUNTIME_PATH}"/patch/package
        chmod 750 "${RUNTIME_PATH}"/patch/package
        chown ICUser:LEGO "${RUNTIME_PATH}"/patch/package
    fi

    if [[ ! -f ${patchVersionFile} ]]; then
        touch "${patchVersionFile}"
        chmod 400 "${patchVersionFile}"
        chown ICUser:LEGO "${patchVersionFile}"
    fi

    echo -e "PATCH_VER=OceanStor BCManager 8.5.0.SPC200" > "${patchVersionFile}"
    echo -e "copyright=huawei" >> "${patchVersionFile}"
}

function startInstall() {
    if [[ "${isBackup}" != "true" ]]; then
        log "Failed to back up the file."
        return 1
    fi

    log "Begin to replace jar..."
    replace_8_5_0_cp1_jars
    log "Replace jars successfully."
	
	log "Begin add properties..."
    replace_properties_file
    log "add properties successfully."
	
	log "Begin replace shell..."
    setUserEnv
    log "replace shell successfully."

    log "Begin alter DataBase..."
    startGaussDb
    alterDataBase
    [[ $? -eq 0 ]] && log "alter DataBase successfully."
    stopGaussDb

    local -r needRollbackJar=$(cat "${backupRecord}" | grep "need.rollback.jar" | awk -F '=' '{print $2}')
    if [[ "${needRollbackJar}" == "" ]]; then
        echo -e "\nneed.rollback.jar=yes" >> "${backupRecord}"
    else
        sed -i 's/^need.rollback.jar=.*/need.rollback.jar=yes/' "${backupRecord}"
    fi

    backUpPatchVersion
    installStatus="true"
    log "Install patch successfully."
    return 0
}


function replace_properties_file() {
	
    if [[ -f ${legoPropertiesFile} ]]; then
        echo -e "monitor.kube.resource.controller.duration=5" >> "${legoPropertiesFile}"
		echo -e "monitor.kube.resource.controller.timeout=30" >> "${legoPropertiesFile}"
    fi
	
}

function startGaussDb(){
    /etc/init.d/gaussdb status | grep -q "no server running"
    gaussDbStatus=$?
    if [ ${gaussDbStatus} == "0" ]; then
        log "Start GaussDB."
        /etc/init.d/gaussdb start >> ${logfile}
    fi
}

function stopGaussDb(){
    if [ ${gaussDbStatus} == "0" ]; then
        log "Stop GaussDB."
        /etc/init.d/gaussdb stop >> ${logfile}
    fi
}

function getDBAuthInfo() {
    echo -e "Please input the database DBUser(default with input nothing: GaussDB): "
    stty -echo
    read -s managerUserName
    stty  echo
    if [ -z "${managerUserName}" ]; then
        managerUserName=GaussDB
    fi

    echo -e "Please input the database port(default with input nothing: 6432): "
    stty -echo
    read -s dbPort
    stty  echo
    if [ -z "${dbPort}" ]; then
        dbPort=6432
    fi

    echo -e "Please input the database admin(GaussDB) password: "
    stty -echo
    read -s managerPassword
    stty  echo
    local loop_index
    loop_index=0
    while true;
    do
        if [ -z "${managerPassword}" ]; then
            if [ "$loop_index" -eq 3 ]; then
                echo ""
                echo -e "The password input empty much times. Exit."
                log "Password input empty much times, exiting."
                exit 1
            fi
            loop_index=$((loop_index + 1))
            echo ""
            read -s -p "The password is empty. Please try again." managerPassword
        else
            break
        fi
    done
    managerPassword=$(echo "$managerPassword" | tr -d '"')
    managerUserName=$(echo "$managerUserName" | tr -d '"')
    dbPort=$(echo "$dbPort" | tr -d '"')

    log "The input GaussDB managerUserName: $managerUserName, workPort: $dbPort."
}

function recordSql() {
    local index=$1
    local type=$2
    if [[ ! -f ${backupRecord} ]]; then
        log "Not find record file, exit"
        return 1
    fi
    if [[ "${type}" == "drop" ]]; then
        sed -i 's/^update.sql.index_'${index}'=.*/update.sql.index_'${index}'=no/' ${backupRecord}
        return 0
    fi
    local idxRes=`cat ${backupRecord} | grep "update.sql.index_${index}" | awk -F '=' '{print $2}'`
    if [[ "${idxRes}" == "" ]]; then
        echo -e "\nupdate.sql.index_${index}=no" >> ${backupRecord}
    fi

    sed -i 's/^update.sql.index_'${index}'=.*/update.sql.index_'${index}'=yes/' ${backupRecord}
}

function replace_8_5_0_cp1_jars() {
    log "Begin to replace 8.5.0 jars..."

    chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
	
	chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f "${CURR_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar

	chattr -i "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
	chattr -i "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    cp -f "${CURR_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${NODEAGENT_PATH}"/lib/
    cp -f "${CURR_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f "${CURR_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
	chattr +i "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar

    chattr -i "${NODEAGENT_PATH}"/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
	cp -f "${CURR_PATH}"/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommon}"
	cp -f "${CURR_PATH}"/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommonTomcat}"
	cp -f "${CURR_PATH}"/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommonNodeAgent}"
	chmod 400 "${ubaseCoreSDKCommon}"
	chmod 400 "${ubaseCoreSDKCommonTomcat}"
	chmod 400 "${ubaseCoreSDKCommonNodeAgent}"
    chown ICUser:LEGO "${ubaseCoreSDKCommon}"
    chown ICUser:LEGO "${ubaseCoreSDKCommonTomcat}"
    chown ICUser:LEGO "${ubaseCoreSDKCommonNodeAgent}"
    chattr +i "${NODEAGENT_PATH}"/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar

    cp -f "${CURR_PATH}"/DRM-Base-Bundle-0.0.1-SNAPSHOT.jar "${baseJar}"
    chmod 400 "${baseJar}"
    chown ICUser:LEGO "${baseJar}"

    cp -f "${CURR_PATH}"/DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar "${storageJar}"
    chmod 400 "${storageJar}"
    chown ICUser:LEGO "${storageJar}"

    cp -f "${CURR_PATH}"/DRM-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${commonJar}"
    chmod 400 "${commonJar}"
    chown ICUser:LEGO "${commonJar}"

    cp -f "${CURR_PATH}"/DRM-Kubernetes-Manager-Bundle-0.0.1-SNAPSHOT.jar "${kubernetesJar}"
    chmod 400 "${kubernetesJar}"
    chown ICUser:LEGO "${kubernetesJar}"

    cp -f "${CURR_PATH}"/DRM-Storage-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${storageCommonJar}"
    chmod 400 "${storageCommonJar}"
    chown ICUser:LEGO "${storageCommonJar}"

    cp -f "${CURR_PATH}"/DRM-Oracle-Manager-Bundle-0.0.1-SNAPSHOT.jar "${oracleJar}"
    chmod 400 "${oracleJar}"
    chown ICUser:LEGO "${oracleJar}"

    cp -f "${CURR_PATH}"/DRM-Database-Base-Bundle-0.0.1-SNAPSHOT.jar "${databaseJar}"
    chmod 400 "${databaseJar}"
    chown ICUser:LEGO "${databaseJar}"

    cp -f "${CURR_PATH}"/DRM-HW-CDR-Bundle-0.0.1-SNAPSHOT.jar "${CDRJar}"
    chmod 400 "${CDRJar}"
    chown ICUser:LEGO "${CDRJar}"
	
	cp -f "${CURR_PATH}"/DRM-Host-Bundle-0.0.1-SNAPSHOT.jar "${hostJar}"
	chmod 400 "${hostJar}"
    chown ICUser:LEGO "${hostJar}"
	
	cp -f "${CURR_PATH}"/DRM-vSphere-Bundle-0.0.1-SNAPSHOT.jar "${vsphereJar}"
	chmod 400 "${vsphereJar}"
    chown ICUser:LEGO "${vsphereJar}"
	
	cp -f "${CURR_PATH}"/DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar "${hwHvsSraJar}"
	chmod 400 "${hwHvsSraJar}"
    chown ICUser:LEGO "${hwHvsSraJar}"

    cp -f "${CURR_PATH}"/rd_base.jar "${rdBaseJar}"
    chmod 400 "${rdBaseJar}"
    chown ICUser:LEGO "${rdBaseJar}"

    cp -f "${CURR_PATH}"/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${i18nBackendJar}"
    chmod 400 "${i18nBackendJar}"
    chown ICUser:LEGO "${i18nBackendJar}"

    cp -f "${CURR_PATH}"/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${i18nFrontJar}"
    chmod 400 "${i18nFrontJar}"
    chown ICUser:LEGO "${i18nFrontJar}"

    cp -f "${CURR_PATH}"/fusionsphere.jar "${fusionsphereJar}"
    chmod 400 "${fusionsphereJar}"
    chown ICUser:LEGO "${fusionsphereJar}"

    log "Replace 8.5.0 jars successfully."
}

function backupOriginal() {
    log "Begin to backup files..."
    cd "$CURR_PATH" || exit 1

    if [[ ! -d backupPath ]]; then
        mkdir -p backupPath
        touch "${backupRecord}"
        echo -e "has.backup.files=no" >> "${backupRecord}"
    fi

    local -r flag=$(cat ${backupRecord} | grep "has.backup.files" | awk -F '=' '{print $2}')
    if [[ "${flag}" == "yes" ]]; then
        isBackup="true"
        log "Already exist backup files."
        return 0
    fi

    # Already installed a patch, then back up the patch version which will be used in rollback
    if [[ -f ${patchVersionFile} ]]; then
        cp "${patchVersionFile}" ./backupPath/
    fi
	
	# Already installed a patch, then back up the properties file which will be used in rollback
    if [[ -f ${legoPropertiesFile} ]]; then
        cp "${legoPropertiesFile}" ./backupPath/
    fi

    # backup 8.5.0 jars
    cp "${baseJar}" ./backupPath/
    cp "${kubernetesJar}" ./backupPath/
    cp "${storageCommonJar}" ./backupPath/
    cp "${oracleJar}" ./backupPath/
    cp "${databaseJar}" ./backupPath/
    cp "${CDRJar}" ./backupPath/
	cp "${hostJar}" ./backupPath/
    cp "${rdBaseJar}" ./backupPath/
    cp "${coreSdkJar}" ./backupPath/
	cp "${vsphereJar}" ./backupPath/
	cp "${hwHvsSraJar}" ./backupPath/
	cp "${ubaseCoreSDKCommon}" ./backupPath/
	cp "${legoCoreBaseCommonJar}" ./backupPath/
	cp "${coreCommonJar}" ./backupPath/
    cp "${storageJar}" ./backupPath/
    cp "${commonJar}" ./backupPath/
	cp "${i18nBackendJar}" ./backupPath/
    cp "${i18nFrontJar}" ./backupPath/
    cp "${fusionsphereJar}" ./backupPath/

    log "Backup 8.5.0 jars successfully."

    isBackup="true"
    sed -i 's/^has.backup.files=.*/has.backup.files=yes/' ${backupRecord}
    log "File backup completed."
}

function alterDataBase() {
    if [[ "${isBackup}" != "true" ]]; then
        log "Failed to back up the file, exit"
        return 1
    fi
    local sqlIndex1=`cat ${backupRecord} | grep "update.sql.index_1" | awk -F '=' '{print $2}'`
    local sqlIndex2=`cat ${backupRecord} | grep "update.sql.index_2" | awk -F '=' '{print $2}'`
    local sqlIndex3=`cat ${backupRecord} | grep "update.sql.index_3" | awk -F '=' '{print $2}'`
    if [ "${sqlIndex1}" = "yes" ] && [ "${sqlIndex2}" = "yes" ] && [ "${sqlIndex3}" = "yes" ]; then
        log "No need to alter DB column, all be done."
        return 0
    fi

    getDBAuthInfo

    if [[ "${sqlIndex1}" != "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_ORACLEADGCONFIGSUBPROCESSOR ALTER COLUMN LUNMAPPING TYPE VARCHAR(10240);' &>/dev/null
        ret1=$?
        if [[ ${ret1} -ne 0 ]]; then
            log "Failed to alter TI_ORACLEADGCONFIGSUBPROCESSOR."
            return 1
        fi
        recordSql 1 "add"
    fi

    if [[ "${sqlIndex2}" != "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR ADD COLUMN SNAPSHOT_ID VARCHAR(255);' &>/dev/null
        ret2=$?
        if [[ ${ret2} -ne 0 ]]; then
            log "Failed to alter SNAPSHOT_ID of TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR."
            isNeedRollbackDB="true"
            return 1
        fi
        recordSql 2 "add"
    fi

    if [[ "${sqlIndex3}" != "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR ADD COLUMN SNAPSHOT_NAME VARCHAR(255);' &>/dev/null
        ret3=$?
        if [[ ${ret3} -ne 0 ]]; then
            log "Failed to alter SNAPSHOT_NAME of TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR."
            isNeedRollbackDB="true"
            return 1
        fi
        recordSql 3 "add"
    fi

    log "Alter DB column successfully!"
    return 0
}


function rollBackDB() {
    local sqlIndex1=`cat ${backupRecord} | grep "update.sql.index_1" | awk -F '=' '{print $2}'`
    local sqlIndex2=`cat ${backupRecord} | grep "update.sql.index_2" | awk -F '=' '{print $2}'`
    local sqlIndex3=`cat ${backupRecord} | grep "update.sql.index_3" | awk -F '=' '{print $2}'`
    local sqlIndex4=`cat ${backupRecord} | grep "update.sql.index_4" | awk -F '=' '{print $2}'`
    local sqlIndex5=`cat ${backupRecord} | grep "update.sql.index_5" | awk -F '=' '{print $2}'`
    if [ "${sqlIndex1}" != "yes" ] && [ "${sqlIndex2}" != "yes" ] && [ "${sqlIndex3}" != "yes" ] && [ "${sqlIndex4}" != "yes" ] && [ "${sqlIndex5}" != "yes" ]; then
        log "No need to rollback DB column, all be done."
        return 0
    fi

    getDBAuthInfo

    if [[ "${sqlIndex1}" == "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_ORACLEADGCONFIGSUBPROCESSOR ALTER COLUMN LUNMAPPING TYPE VARCHAR(255);' &>/dev/null
        res1=$?
        if [[ ${res1} -ne 0 ]]; then
            log "Failed to rollBack TI_ORACLEADGCONFIGSUBPROCESSOR."
            return 1
        fi
        recordSql 1 "drop"
    fi

    if [[ "${sqlIndex2}" == "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR DROP COLUMN IF EXISTS SNAPSHOT_ID;' &>/dev/null
        res2=$?
        if [[ ${res2} -ne 0 ]]; then
            log "Failed to rollBack TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR SNAPSHOT_ID."
            return 1
        fi
        recordSql 2 "drop"
    fi

    if [[ "${sqlIndex3}" == "yes" ]]; then
        echo ${managerPassword} | /usr/local/gaussdb/bin/gsql -d LEGO -U ${managerUserName} -p ${dbPort} -c 'ALTER TABLE IF EXISTS TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR DROP COLUMN IF EXISTS SNAPSHOT_NAME;' &>/dev/null
        res3=$?
        if [[ ${res3} -ne 0 ]]; then
            log "Failed to rollBack TI_CREATE_SNAPSHOT_BACKUP_COPY_SUB_PROCESSOR SNAPSHOT_NAME."
            return 1
        fi
        recordSql 3 "drop"
    fi

    log "RollBack DB successfully!!!"
}

function rollBackJar() {
    local rollbackJar
    rollbackJar=$(cat "${backupRecord}" | grep "need.rollback.jar" | awk -F '=' '{print $2}')
    if [[ "${rollbackJar}" != "yes" ]]; then
        log "No need to rollback jars."
        return 0
    fi

    cd "${CURR_PATH}"/backupPath/ || exit 1
    log "Begin to rollBack jars."
    rollback_8_5_0_cp1_jars

    local -r needRollbackJar=$(cat ${backupRecord} | grep "need.rollback.jar" | awk -F '=' '{print $2}')
    if [[ "${needRollbackJar}" == "yes" ]]; then
        sed -i 's/^need.rollback.jar=.*/need.rollback.jar=no/' ${backupRecord}
    fi

    cd "${CURR_PATH}" || exit 1
    log "RollBack patch jar successfully."
	
	# properties files
	if [[ -f "${CURR_PATH}"/backupPath/lego.properties ]]; then
        cp -f "${CURR_PATH}"/backupPath/lego.properties "${legoPropertiesFile}"
	fi
	
    if [[ -f "${CURR_PATH}"/backupPath/patchVersion.conf ]]; then
        cp -f "${CURR_PATH}"/backupPath/patchVersion.conf "${patchVersionFile}"
    else
        rm -f "${patchVersionFile}" &>/dev/null
        rm -rf "${RUNTIME_PATH}/patch/package" &>/dev/null
    fi

    rollbackStatus="true"
    return 0
}

function rollback_8_5_0_cp1_jars() {
    log "Begin to rollback 8.5.0.SPC200 jars..."
    chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    cp -f DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/
    cp -f DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
	
	chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    cp -f DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/
    cp -f DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${TOMCAT_PATH}"/Lego-UI-Plat/WEB-INF/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar

	chattr -i "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
	chattr -i "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    cp -f Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${NODEAGENT_PATH}"/lib/
    cp -f Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${BIN_PATH}"/lib/
    cp -f Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${PLUGINS_PATH}"/
    chmod 400 "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chmod 400 "${PLUGINS_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chown ICUser:LEGO "${PLUGINS_PATH}"/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
	chattr +i "${NODEAGENT_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar
    chattr +i "${BIN_PATH}"/lib/Lego-Core-Base-Common-Bundle-0.0.1-SNAPSHOT.jar

    chattr -i "${NODEAGENT_PATH}"/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar
	cp -f UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommon}"
	cp -f UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommonTomcat}"
	cp -f UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar "${ubaseCoreSDKCommonNodeAgent}"
	chmod 400 "${ubaseCoreSDKCommon}"
	chmod 400 "${ubaseCoreSDKCommonTomcat}"
	chmod 400 "${ubaseCoreSDKCommonNodeAgent}"
    chown ICUser:LEGO "${ubaseCoreSDKCommon}"
    chown ICUser:LEGO "${ubaseCoreSDKCommonTomcat}"
    chown ICUser:LEGO "${ubaseCoreSDKCommonNodeAgent}"
    chattr +i "${NODEAGENT_PATH}"/lib/UBase-Core-SDK-Common-Bundle-0.0.1-SNAPSHOT.jar

    cp -f DRM-Base-Bundle-0.0.1-SNAPSHOT.jar "${baseJar}"
    chmod 400 "${baseJar}"
    chown ICUser:LEGO "${baseJar}"

    cp -f DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar "${storageJar}"
    chmod 400 "${storageJar}"
    chown ICUser:LEGO "${storageJar}"

    cp -f DRM-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${commonJar}"
    chmod 400 "${commonJar}"
    chown ICUser:LEGO "${commonJar}"

    cp -f DRM-Kubernetes-Manager-Bundle-0.0.1-SNAPSHOT.jar "${kubernetesJar}"
    chmod 400 "${kubernetesJar}"
    chown ICUser:LEGO "${kubernetesJar}"

    cp -f DRM-Storage-Base-Common-Bundle-0.0.1-SNAPSHOT.jar "${storageCommonJar}"
    chmod 400 "${storageCommonJar}"
    chown ICUser:LEGO "${storageCommonJar}"

    cp -f DRM-Oracle-Manager-Bundle-0.0.1-SNAPSHOT.jar "${oracleJar}"
    chmod 400 "${oracleJar}"
    chown ICUser:LEGO "${oracleJar}"

    cp -f DRM-Database-Base-Bundle-0.0.1-SNAPSHOT.jar "${databaseJar}"
    chmod 400 "${databaseJar}"
    chown ICUser:LEGO "${databaseJar}"

    cp -f DRM-HW-CDR-Bundle-0.0.1-SNAPSHOT.jar "${CDRJar}"
    chmod 400 "${CDRJar}"
    chown ICUser:LEGO "${CDRJar}"
	
	cp -f DRM-Host-Bundle-0.0.1-SNAPSHOT.jar "${hostJar}"
    chmod 400 "${hostJar}"
    chown ICUser:LEGO "${hostJar}"
	
	cp -f DRM-vSphere-Bundle-0.0.1-SNAPSHOT.jar "${vsphereJar}"
    chmod 400 "${vsphereJar}"
    chown ICUser:LEGO "${vsphereJar}"
	
	cp -f DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar "${hwHvsSraJar}"
    chmod 400 "${hwHvsSraJar}"
    chown ICUser:LEGO "${hwHvsSraJar}"

    cp -f rd_base.jar "${rdBaseJar}"
    chmod 400 "${rdBaseJar}"
    chown ICUser:LEGO "${rdBaseJar}"

    cp -f Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${i18nFrontJar}"
    chmod 400 "${i18nFrontJar}"
    chown ICUser:LEGO "${i18nFrontJar}"

    cp -f Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${i18nBackendJar}"
    chmod 400 "${i18nBackendJar}"
    chown ICUser:LEGO "${i18nBackendJar}"

    cp -f fusionsphere.jar "${fusionsphereJar}"
    chmod 400 "${fusionsphereJar}"
    chown ICUser:LEGO "${fusionsphereJar}"

    log "Rollback 8.5.0.SPC200 jars successfully."
}

function rollbackAll() {
    log "Begin to execute the rollback..."

    if [[ ! -f ${backupRecord} ]]; then
        log "Not find record file, exit."
        return 1
    fi

    local -r hasBackup=$(cat ${backupRecord} | grep "has.backup.files" | awk -F '=' '{print $2}')
    if [[ "${hasBackup}" != "yes" ]]; then
        log "Not backup files, can not rollback!!"
        return 1
    fi

    startGaussDb
    rollBackDB
    if [ $? -ne 0 ]; then
        log "RollBack GaussDB failed, exist 1, check and reset."
        stopGaussDb
        return 1
    fi
	stopGaussDb

    rollBackJar
    if [ $? -ne 0 ]; then
        log "RollBackJar failed, exist 1, check and reset."
        return 1
    fi
}

function main() {
  echo -e "1. Install the upgrade patch."
  echo -e "2. RollBack the patch."
  iChoose=""
  while [ ! "$iChoose" = "1" ] && [ ! "$iChoose" = "2" ]
  do
     read -p "Please select the operation you want to perform. (1/2): " iChoose
  done

  if [ "${iChoose}" == "2" ]; then
      rollbackAll
      if [ "${rollbackStatus}" == "true" ]; then
          echo "Please restart DR system to make the configuration effective."
          rollbackSure=""
          while [ ! "$rollbackSure" = "y" ] && [ ! "$rollbackSure"  = "n" ]
          do
              read -p "RollBack patch successfully, are you sure to start up the software immediately? (y/n)" rollbackSure
          done
          if [ "$rollbackSure" = "y" ];then
              cd "${BIN_PATH}" || exit 1
              sh shutdownSystem.sh y
              sh startSystem.sh y
          fi
          return 0
      fi
      log "Exec rollback patch failed, check and retry."
      exit 1
  fi

  iTmp=""
  while [ ! "$iTmp" = "y" ] && [ ! "$iTmp" = "n" ]
  do
     read -p "Are you sure you want to install the new patch? (y/n): " iTmp
  done
  if [ "$iTmp" = "y" ];then
      backupOriginal
      startInstall
      if [ $? -ne 0 ]; then
          log "Patch jar failed, exist 1, check and reset."
          return 1
      fi
  fi

  echo ""
  if [ "${installStatus}" == "true" ]; then
      echo "Please restart DR system to make the configuration effective."
      sure=""
      while [ ! "$sure" = "y" ] && [ ! "$sure"  = "n" ]
      do
          read -p "Are you sure to start up the software immediately? (y/n)" sure
      done
      if [ "$sure" = "y" ]; then
          cd "$BIN_PATH" || exit 1
          sh ./shutdownSystem.sh y
          sh startSystem.sh y
      fi
  fi
}

main
if [ $? -ne 0 ]; then
    log "Install patch failed!!!"
    if [ "${installStatus}" == "true" ]; then
        failedRollBack=""
        while [ ! "$failedRollBack" = "y" ] && [ ! "$failedRollBack"  = "n" ]
        do
            read -p "Are you sure to rollback immediately? (y/n)" failedRollBack
        done
        if [ "${failedRollBack}" = "y" ]; then
            rollbackAll
        fi
    fi
fi
