#!/bin/bash
################################################################################
# Copyright © Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
#
# Description: suse操作系统双区升级核心代码，提供备份和升级能力
#
# Usage： bash rollback.sh
#
# Exitcode：0成功，1失败
#
#################################################################################

# 加载依赖模块
source "${WORKSPACE}/online/env.propertity"
source "${WORKSPACE}/online/common.sh"

# 升级 回滚前需要增加解锁操作
function recover_boot_menu(){
    # 先从/boot_backup目录中恢复boot文件，避免同内核版本initrd文件相互覆盖
    cp -arf /boot_backup/* /boot/

    grub2-set-default "${OLD_VERSION_GRUB_MENU}" 2>&1 >> "${ROLLBACK_LOG_FILE}"
    if [ $? -ne 0 ]; then
        log "ERROR" "Set default grub menu as ${OLD_VERSION_GRUB_MENU} failed!" "${ROLLBACK_LOG_FILE}"
        return 1
    fi
}

function main()
{
    init_log "${ROLLBACK_LOG_FILE}"

    check_is_upgrade 
    local upgrade_status=$?
    if [ ${upgrade_status} -eq ${UPGRADE_NOT_REBOOTED_CODE} ]; then
        log "INFO" "The patch has been installed but not effective yet, no need to rollback, skip the rollback process!" "${ROLLBACK_LOG_FILE}"
        return 0
    elif [ ${upgrade_status} -eq ${NOT_UPGRADE_NOT_REBOOTED_CODE} ];then
        log "INFO" "The patch has not been installed yet, no need to rollback, skip the rollback process!" "${ROLLBACK_LOG_FILE}"
        return 0
    else
        log "INFO" "Start to rollback os, please wait..." "${ROLLBACK_LOG_FILE}"
    fi

    stop_lock_service "${UPGRADE_LOG_FILE}" || return 1

    recover_boot_menu || return 1
}

main 
exit $?