#!/usr/bin/env bash
#########################################################
# Copyright © Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
# File name     : upgrade_rollback_func.sh
# Description   : 欧方升级公共函数脚本
###########################################################

# 企业定制了sudobin目录为/opt/sudobin，升级/回滚时，需要识别sudobin的路径
ENV_SOURCE_FILE=/opt/oss/manager/bin/engr_profile.sh
[ -f "${ENV_SOURCE_FILE}" ] && . "${ENV_SOURCE_FILE}"
# 如果脚本加载成功，SUPER_ROOT变量即为企业的sudobin路径
if [ -z "${SUPER_ROOT}" ];then
    SUDOBIN_PATH=/usr/local/uniepsudobin/
else
    SUDOBIN_PATH="${SUPER_ROOT}"
fi

# sudoconfig的解压路径
SUDOCONFIG_PATH=""
# osconfig的解压路径
OSCONFIG_PATH=""
# 需要被清理的目录的创建时长
EXPIRERATED_DAYS=31
# 需要清理的目录,包含平台osconfig的备份目录，欧方的升级目录，之前版本管理节点的package目录
DIRECTORY_PATTERN="bak_* upgrade_config_* package"

############################################################
# Name:        unzip_cloudsop_pack
# Description: 解压CloudSOP的osconfig和sudoconfig包
############################################################
function unzip_cloudsop_pack(){
    local sudoconfig_pack="$(ls ${CURRENT_DIR}/sudoconfig_*.tar.gz)"
    if [ ! -f "${sudoconfig_pack}" ]; then
        print_log "ERROR" "${sudoconfig_pack} package is not exist."
        return 1
    fi

    SUDOCONFIG_PATH="${CURRENT_DIR}/../sudoconfig"
    [ -d "${SUDOCONFIG_PATH}" ] && rm -rf "${SUDOCONFIG_PATH}"
    mkdir -p "${SUDOCONFIG_PATH}"
    if [ $? -ne 0 ];then
        print_log "ERROR" "mkdir ${SUDOCONFIG_PATH} is failed."
        return 1
    fi
    print_log "INFO" "mkdir ${SUDOCONFIG_PATH} is finished."

    tar xvfz "${sudoconfig_pack}" -C "${SUDOCONFIG_PATH}" --no-same-owner >/dev/null 2>&1
    if [ $? -ne 0 ];then
        print_log "ERROR" "unzip ${sudoconfig_pack} to ${SUDOCONFIG_PATH} is failed."
        return 1
    fi
    local osconfig_pack=
    print_log "INFO" "current os type is ${OS_TYPE}."
    if [ "${OS_TYPE}" = "suse" ]; then
        osconfig_pack=$(ls ${CURRENT_DIR}/osconfig-*.zip | grep -vi euler)
    elif [ "${OS_TYPE}" = "euler" ] || [ "${OS_TYPE}" = "kylin" ] || [ "${OS_TYPE}" = "centos" ] || [ "${OS_TYPE}" = "CTyunOS" ]; then
        osconfig_pack=$(ls ${CURRENT_DIR}/osconfig-*.zip | grep -i euler)
    else
        print_log "ERROR" "can not support OS type, only support euler suse kylin centos."
        return 1
    fi

    if [ ! -f "${osconfig_pack}" ];then
        print_log "ERROR" "${osconfig_pack} package is not exist."
        return 1
    fi

    OSCONFIG_PATH="${CURRENT_DIR}/../osconfig"
    [ -d "${OSCONFIG_PATH}" ] && rm -rf ${OSCONFIG_PATH}
    mkdir -p "${OSCONFIG_PATH}"
    if [ $? -ne 0 ];then
        print_log "ERROR" "mkdir ${OSCONFIG_PATH} is failed."
        return 1
    fi
    print_log "INFO" "mkdir ${OSCONFIG_PATH} is finished."

    unzip -d ${OSCONFIG_PATH} -o ${osconfig_pack} >/dev/null 2>&1
    if [ $? -ne 0 ];then
        print_log "ERROR" "unzip ${osconfig_pack} to ${OSCONFIG_PATH} is failed."
        return 1
    fi
    # 复制扩展包
    cp ${CURRENT_DIR}/custom-* ${OSCONFIG_PATH}/ >/dev/null 2>&1
    cp ${CURRENT_DIR}/framework-* ${OSCONFIG_PATH}/ >/dev/null 2>&1
    cp ${CURRENT_DIR}/default-* ${OSCONFIG_PATH}/ >/dev/null 2>&1
    chown -R ossadm:ossgroup "${SUDOCONFIG_PATH}"
    chown -R ossadm:ossgroup "${OSCONFIG_PATH}"
    return 0
}

############################################################
# Name:        print_log
# Description: 打印日志
# @Param1:     日志级别：INFO WARN ERROR
# @Param2:     日志内容
############################################################
function print_log() {
    local log_level=$1
    local log_info=$2
    echo "[$(date)] | [${log_level}]: ${log_info}"
}

############################################################
# Description: 获取定制的参数
############################################################
function get_custom_para() {
    # 获取参数 有定制参数时 采用定制参数值
    while [ $# -gt 0 ];
    do
        case "${1}" in
            -isConnectInet)
                case "$2" in
                    "true")
                        BUILD_FLAG=build-inet;
                        shift 2;
                        ;;
                    *)
                        shift 2;
                        ;;
                esac
                 ;;
            -wireless)
                case "$2" in
                    "wireless_install")
                        WIRELESS=yes;
                        shift 2;
                        ;;
                    *)
                        WIRELESS=no;
                        shift 2;
                        ;;
                esac
                 ;;
            *)
                shift
                continue
                ;;
        esac
    done
}

############################################################
# Name:        cmp_time_stamp
# Description: 对比目录的modify时间戳和当前系统时间的差异，如果时间戳早于
#              当前时间戳${EXPIRERATED_DAYS}天，返回0，否则返回1
# @Param1:     目录名
# @Return：    0/1
############################################################
function cmp_time_stamp() {
    local dir="$1"
    # 目录判断
    [ ! -d "${CURRENT_DIR}/../${dir}" ] && return 1
    # 当前时间距离1970-01-01 00:00:00 UTC的秒数
    local current_time="$(date +%s -d "$(date)")"
    # 目录更新时间距离1970-01-01 00:00:00 UTC的秒数
    local dir_modify_time="$(date +%s -d "$(stat -c %y ${CURRENT_DIR}/../${dir})")"
    local seconds_diff="$(expr "${current_time}" - "${dir_modify_time}")"
    print_log "INFO" "time different of $(date) between ${dir}'s modify time is ${seconds_diff} seconds."

    local days_diff=$(expr "${seconds_diff}" / 3600 / 24)
    # 判断时间差异是否大于${EXPIRERATED_DAYS}天
    if [ ! -z "${days_diff}" ] && [ "${days_diff}" -gt "${EXPIRERATED_DAYS}" ];then
        print_log "INFO" "${CURRENT_DIR}/../${dir} need to remove."
        return 0
    fi
    return 1
}

############################################################
# Name:        clean_path
# Description: 升级完成，因21.1-22.1版本的升级目录升级完成未清理，且高版本升级完成仍保留目录
#              所以需要删除创建时间距当前时间差超过${EXPIRERATED_DAYS}天的升级目录
#              (含平台的备份目录bak_xxx，以及升级目录upgrade_xxx)
############################################################
function clean_after_upgrade() {
    print_log "INFO" "work directory:${CURRENT_DIR}, start to clean."
    cd "${CURRENT_DIR}"/../
    # 删除需要清理的目录，目录匹配根据${DIRECTORY_PATTERN}
    local dir_list=$(ls -d ${DIRECTORY_PATTERN})
    for dir in ${dir_list};do
        cmp_time_stamp "${dir}"
        if [ $? -eq 0 ];then
            rm -rf "${CURRENT_DIR}/../${dir}"
            print_log "INFO" "success to remove ${CURRENT_DIR}/../${dir}."
        fi
    done
    print_log "INFO" "finish to clean unused directory in $(realpath ${CURRENT_DIR}/../)."
}

############################################################
# Name:        clean_after_rollback
# Description: 删除平台osconfig的备份目录，避免同版本换包反复升级回滚，无法持续备份
############################################################
function clean_after_rollback() {
    print_log "INFO" "start to clean directory after rollback."
    local osconfig_bak_path="${CURRENT_DIR}/../bak_${VERSION}"
    [ -d "${osconfig_bak_path}" ] && rm -rf "${osconfig_bak_path}"
    print_log "INFO" "finish to clean directory after rollback."
}

############################################################
# Name:        modify_file_perm
# Description: 刷新权限，要求普通文件权限为640，脚本权限为550，签名文件
#              权限最多为600
############################################################
function modify_file_perm() {
    print_log "INFO" "start to change file permission."
    # 修改文件权限
    chmod 640 "${CURRENT_DIR}"/*
    chmod 550 "${CURRENT_DIR}"/*.sh
    chmod 600 "${CURRENT_DIR}"/*.crl
    chmod 600 "${CURRENT_DIR}"/*.cms
    print_log "INFO" "finish to change file permission."
}