#!/bin/bash

###############################################################################
# Copyright © Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
# File name: install_mellanox.sh
# Description: 安装Mellanox驱动，重启网络，重启DPDKAgent
###############################################################################

CUR_PATH=$(cd `dirname $0`;pwd)
rm -f ${CUR_PATH}/grub_config_flag
systemctl status lock| grep Process &>/dev/null
if [[ $? == 0 ]];
then
  systemctl stop lock &>/dev/null
  logger -p local0.info "$(who -m | cut -d\( -f2 |cut -d\) -f1)  [stop lock service"
fi
logger -p local0.info "$(who -m | cut -d\( -f2 |cut -d\) -f1)  [install mellanox driver]Start updating mellanox driver"
param=$1
echo "Start updating mellanox driver"
ls "$CUR_PATH"/kmod-mlnx-ofa_kernel-* &>/dev/null
if [[ $? != 0 ]];
then
  echo "please upload package of Mellanox"
  touch ${CUR_PATH}/mellanox_install_failed
  exit 1
fi

ls -l "$CUR_PATH" |grep "libibverbs-" |grep -v "utils" &>/dev/null
if [[ $? != 0 ]];
then
  echo "please upload package of Mellanox"
  touch ${CUR_PATH}/mellanox_install_failed
  exit 1
fi

libibverbsRpmName=$(ls -l "$CUR_PATH" |grep "libibverbs-" |grep -v "utils" |awk '{print $9}')
echo "install $libibverbsRpmName"
rpm -e libibverbs-* &>/dev/null
rpm -ivh --force --nodeps "$CUR_PATH"/"$libibverbsRpmName"

kmodRpmName=$(ls -l "$CUR_PATH" |grep kmod-mlnx-ofa |awk '{print $9}')
echo "install $kmodRpmName"
rpm -e kmod-mlnx-ofa_kernel-* &>/dev/null
rpm -ivh --force --nodeps "$CUR_PATH"/"$kmodRpmName"

modprobe -r mlx5_ib
modprobe -r mlx5_core
modprobe -r ib_uverbs

koLocationExample=$(rpm -ql "$CUR_PATH"/"$kmodRpmName" 2> /dev/null |grep "/lib/modules" |tail -1)
koLocationBase="${koLocationExample%extra*}"
cp -r "$koLocationBase""/extra/mlnx-ofa_kernel" "/lib/modules/""$(uname -r)""/extra"
depmod -a

modprobe ib_uverbs
modprobe mlx5_core
modprobe mlx5_ib

modinfo mlx5_core |grep version

echo "Mellanox driver updated successfully"

service network restart

if [[ ${param} != "no_restart_app" ]]
then
    su - ossadm -c ". /opt/oss/manager/bin/engr_profile.sh;ipmc_adm -cmd restartapp -app DPDKAgent"
    su - ossadm -c ". /opt/oss/manager/bin/engr_profile.sh;ipmc_adm -cmd restartapp -app AnlyFlowCollectService"
fi

touch ${CUR_PATH}/mellanox_install_success

logger -p local0.info "$(who -m | cut -d\( -f2 |cut -d\) -f1)  [install mellanox driver]Start to update system aide info"
aide -c /etc/aide.d/aide_os.conf --update
mv /var/lib/aide/aide_os.db.new.gz /var/lib/aide/aide_os.db.gz
logger -p local0.info "$(who -m | cut -d\( -f2 |cut -d\) -f1)  [install mellanox driver]End to update system aide info"

logger -p local0.info "$(who -m | cut -d\( -f2 |cut -d\) -f1)  [install mellanox driver]Mellanox driver updated successfully"
