#!/bin/bash

###############################################################################
# Copyright © Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
# File name: disk_partition.sh
# Description: 安装操作系统补丁rpm包
###############################################################################
LOG_FILE="/root/install_config/install_os_patch_pkg.log"
OS_PATCH_PATH="/root/EasySuite/888/*Patch*.tar"
UNZIP_OS_PATCH_PATH="/opt/os_patch"

function logger() {
    log_level=$1
    log_info=$2
    if [[ ${log_level} == "info" ]]; then
        echo [INFO]${log_info} >> ${LOG_FILE}
    elif [[ ${log_level} == "warn" ]]; then
        echo [WARN]${log_info} >> ${LOG_FILE}
    else
        echo [ERROR]${log_info} >> ${LOG_FILE}
    fi
 }

function unzip_os_patch() {
    tar -xvf ${OS_PATCH_PATH} -C ${UNZIP_OS_PATCH_PATH}
    cd ${UNZIP_OS_PATCH_PATH}
    tar -xvf *.tar.gz
    tar -xvf *.tar.gz
    cd *Patch
    tar -xvf os*_pkg.tar
    tar -xvf os_sudobin.tar
}

function install_os_patch() {
    cd ${UNZIP_OS_PATCH_PATH}/*Patch/script
    bash update_*_do.sh install
}

function install_dpdk_dependence_rpm(){
    cd /usr/local/rpmpkg
    rpm -qa |grep numactl-libs
    if [[ $? == 0 ]];then
        logger "warn" "Dpdk dependence rpm package has been installed."
        echo "==============Dpdk dependence rpm package has been installed.==============="
        return 0
    fi
    rpm -ivh numactl-libs-2.*.rpm >/dev/null 2>&1
}

function main() {
    rm -rf ${UNZIP_OS_PATCH_PATH}
    mkdir -p ${UNZIP_OS_PATCH_PATH}
    logger "info" "Start to install the operating system patch package."
    os_type=$(cat /etc/os-release | grep '^NAME'|awk -F'=' '{print $2}')
    if [[ ${os_type} =~ "Kylin Linux Advanced Server" ]];then
        logger "info" "The Kirin OS does not need to be installed with the OS patch package."
        return 0
    fi
    if [[ ${os_type} =~ "SLES" ]];then
        logger "info" "The SUSE OS does not need to be installed with the OS patch package."
        return 0
    fi
    unzip_os_patch
    if [[ $? != 0 ]];then
        logger "error" "Failed to decompress the OS patch package."
        echo "==============Failed to decompress the OS patch package===============" >&2
        return 1
    fi
    install_os_patch
    if [[ $? != 0 ]];then
        logger "error" "Failed to install the OS Patch package"
        echo "==============Failed to install the OS Patch package==================" >&2
        return 1
    fi
    install_dpdk_dependence_rpm
    if [[ $? != 0 ]];then
        logger "error" "Failed to install dpdk dependence package"
        echo "=============Failed to install dpdk dependence package================"
    fi
    logger "info" "End to install the operating system patch package."
    return 0
}

main
