#!/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"
LOGDIR="$CURR_PATH/log"

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

# jars to be replaced
baseJar=${PLUGINS_PATH}/DRM-Base-Bundle-0.0.1-SNAPSHOT.jar
coreSdkJar=${PLUGINS_PATH}/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
hvsSraJar=${PLUGINS_PATH}/DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar
rdBaseJar=${TOMCAT_PATH}/Lego-UI-Plat/WEB-INF/lib/rd_base.jar
storageBaseJar=${PLUGINS_PATH}/DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar
legoI18nJar=${PLUGINS_PATH}/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar
uBaseMedCommonJar=${PLUGINS_PATH}/UBase-Med-Common-Bundle-0.0.1-SNAPSHOT.jar
fsbSraJar=${PLUGINS_PATH}/DRM-HW-FSB-SRA-Bundle-0.0.1-SNAPSHOT.jar

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

if ! [ -d $LOGDIR ];then mkdir $LOGDIR ;fi

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


function createPatchVersionFile() {
    log "Begin to create 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.3.1.CP5" > "${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_3_1_cp5_jars
    log "Replace jars successfully."

    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

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

function replace_8_3_1_cp5_jars() {
    chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar

    cp -f "${CURR_PATH}"/DRM-Base-Bundle-0.0.1-SNAPSHOT.jar "${baseJar}"
    cp -f "${CURR_PATH}"/DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar "${hvsSraJar}"
    cp -f "${CURR_PATH}"/rd_base.jar "${rdBaseJar}"
    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}"/
    cp -f "${CURR_PATH}"/DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar "${storageBaseJar}"
    cp -f "${CURR_PATH}"/Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${legoI18nJar}"
    cp -f "${CURR_PATH}"/UBase-Med-Common-Bundle-0.0.1-SNAPSHOT.jar "${uBaseMedCommonJar}"
    cp -f "${CURR_PATH}"/DRM-HW-FSB-SRA-Bundle-0.0.1-SNAPSHOT.jar "${fsbSraJar}"


    chmod 400 "${baseJar}"
    chmod 400 "${hvsSraJar}"
    chmod 400 "${rdBaseJar}"
    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
    chmod 400 "${storageBaseJar}"
    chmod 400 "${legoI18nJar}"
    chmod 400 "${uBaseMedCommonJar}"
    chmod 400 "${fsbSraJar}"

    chown ICUser:LEGO "${baseJar}"
    chown ICUser:LEGO "${hvsSraJar}"
    chown ICUser:LEGO "${rdBaseJar}"
    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
    chown ICUser:LEGO "${storageBaseJar}"
    chown ICUser:LEGO "${legoI18nJar}"
    chown ICUser:LEGO "${uBaseMedCommonJar}"
    chown ICUser:LEGO "${fsbSraJar}"

    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
}

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

    # backup jars
    cp "${baseJar}" ./backupPath/
    cp "${coreSdkJar}" ./backupPath/
    cp "${hvsSraJar}" ./backupPath/
    cp "${rdBaseJar}" ./backupPath/
    cp "${storageBaseJar}" ./backupPath/
    cp "${legoI18nJar}" ./backupPath/
    cp "${uBaseMedCommonJar}" ./backupPath/
    cp "${fsbSraJar}" ./backupPath/
    log "Backup original jars successfully."

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

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_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."

    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_jars() {
    chattr -i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar

    cp -f DRM-Base-Bundle-0.0.1-SNAPSHOT.jar "${baseJar}"
    cp -f DRM-HW-HVS-SRA-Bundle-0.0.1-SNAPSHOT.jar "${hvsSraJar}"
    cp -f rd_base.jar "${rdBaseJar}"
    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}"/
    cp -f DRM-Storage-Base-Bundle-0.0.1-SNAPSHOT.jar "${storageBaseJar}"
    cp -f Lego-I18N-Bundle-0.0.1-SNAPSHOT.jar "${legoI18nJar}"
    cp -f UBase-Med-Common-Bundle-0.0.1-SNAPSHOT.jar "${uBaseMedCommonJar}"
    cp -f DRM-HW-FSB-SRA-Bundle-0.0.1-SNAPSHOT.jar "${fsbSraJar}"

    chmod 400 "${baseJar}"
    chmod 400 "${hvsSraJar}"
    chmod 400 "${rdBaseJar}"
    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
    chmod 400 "${storageBaseJar}"
    chmod 400 "${legoI18nJar}"
    chmod 400 "${uBaseMedCommonJar}"
    chmod 400 "${fsbSraJar}"

    chown ICUser:LEGO "${baseJar}"
    chown ICUser:LEGO "${hvsSraJar}"
    chown ICUser:LEGO "${rdBaseJar}"
    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
    chown ICUser:LEGO "${storageBaseJar}"
    chown ICUser:LEGO "${legoI18nJar}"
    chown ICUser:LEGO "${uBaseMedCommonJar}"
    chown ICUser:LEGO "${fsbSraJar}"

    chattr +i "${BIN_PATH}"/lib/DRM-Core-SDK-Bundle-0.0.1-SNAPSHOT.jar
}

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

    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
