#!/bin/bash
################################################################################
## Copyright:   HUAWEI Tech. Co., Ltd.
## Filename:    analyzer_uninstall.sh
## Description: uninstall CloudSOP
## Version:     V100R20C10
## Created:     Saturday, 11 28, 2020
################################################################################

# ---------------------------------------------------------------------------- #
#                                  全局变量                                     #
# ---------------------------------------------------------------------------- #
declare -r CURRENT_PATH=$(cd `dirname $0`;pwd)
declare -r SOUTH_ENV_FILE="/opt/oss/manager/etc/sysconf/nodelists.json"
declare -r MCCOMMONSERVICE_PATH="/opt/oss/manager/var/envs/Product-MCCommonService/service/envs/env.properties"
declare -r LOG_FILE="$(dirname $(dirname $(dirname ${CURRENT_PATH})))"/cloud/util/log/log.sh
declare -r CLOUDSOP_UNINSTALL=/opt/oss/manager/agent/tools/shscript/uninstall.sh
declare -r g_logPath=/var/log/insight/install/                         # 日志路径
declare -r g_logFile="install.log"                                     # 日志文件
declare -r g_scriptName="$(basename "${BASH_SOURCE-$0}")"              # 当前脚本名称
declare business_float_ip=""
declare lvs_ip=""
declare ipv6_re='^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$'
declare ipv4_re='^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$'


# ---------------------------------------------------------------------------- #
#                                   脚本导入                                    #
# ---------------------------------------------------------------------------- #
. "${LOG_FILE}" || { echo "[${g_scriptName}:${LINENO}] ERROR: Failed to load ${LOG_FILE}."; exit 1;}



################################################################################
# Function: uninstall_cloudsop
# Description: 卸载CloudSOP管理面
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function uninstall_cloudsop()
{
    showLog_info "${LINENO}" "Start to uninstall CloudSOP Manager...."
    ls -l /opt/oss/ | grep FabricInsight
    if [[ $? == 0 ]];then
        su - ossadm -c 'bash /opt/oss/manager/agent/bin/ipmc_adm -cmd stopapp -tenant FabricInsight'
    fi
    ls -l /opt/oss/ | grep CampusInsight
    if [[ $? == 0 ]];then
        su - ossadm -c 'bash /opt/oss/manager/agent/bin/ipmc_adm -cmd stopapp -tenant CampusInsight'
    fi
    ls -l /opt/oss/ | grep FabricInsightMDA
    if [[ $? == 0 ]];then
        su - ossadm -c 'bash /opt/oss/manager/agent/bin/ipmc_adm -cmd stopapp -tenant FabricInsightMDA'
    fi
    if [ -f ${CLOUDSOP_UNINSTALL} ]; then
        # 卸载管理面失败加固:清理sshd_config
        cat /etc/ssh/sshd_config | grep "^Match User root"  2>&1 >/dev/null
        if [[ $? -eq 0 ]];then
            sed '/AllowGroups root/d' /etc/ssh/sshd_config > /etc/ssh/sshd_config_temp
            mv /etc/ssh/sshd_config_temp /etc/ssh/sshd_config;
            sed '/Match User root/d' /etc/ssh/sshd_config > /etc/ssh/sshd_config_temp
            mv /etc/ssh/sshd_config_temp /etc/ssh/sshd_config;
            chmod 600 /etc/ssh/sshd_config
            service sshd restart
        fi
        su ossadm -c "sh ${CLOUDSOP_UNINSTALL} -f"
        if [[ $? != 0 ]];
        then
            showLog_error "${LINENO}" "Fail to uninstall CloudSOP."
            ps -ef | grep -E 'admrun|ossadm|dbuser|ossuser|ossrun|secuser|iscript|3004' |grep -v osconfig | grep -vw grep | awk '{print $2}' | xargs kill -9
            rm -rf /opt/oss /opt/cloud /opt/redis /opt/zenith /opt/pub /home/ossadm/.ssh/ /home/admrunuser/.ssh/ /var/share/oss/manager
        fi
    fi
    ps -ef | grep ^3004 | awk '{print $2}' | xargs -i kill -9 {}
    showLog_info "${LINENO}" "Success to uninstall CloudSOP Manager."

}


################################################################################
# Function: rm_path
# Description: 删除文件
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function rm_path()
{
    showLog_info "${LINENO}" "Start to remove CloudSOP file."

    rm -rf /opt/CloudProductInstall > /dev/null 2>&1
    rm -rf /opt/CloudSOP_Upgrade > /dev/null 2>&1
    rm -rf /opt/Campustools > /dev/null 2>&1
    rm -rf /opt/oss > /dev/null 2>&1
    rm -rf /opt/pub > /dev/null 2>&1
    rm -rf /opt/patch_manager > /dev/null 2>&1
    rm -rf /opt/backup > /dev/null 2>&1
    rm -rf /opt/NCEICMR > /dev/null 2>&1
    rm -rf /opt/envs > /dev/null 2>&1
    rm -rf /opt/infers > /dev/null 2>&1
    rm -rf /var/log/oss > /dev/null 2>&1
    rm -rf /var/share/oss > /dev/null 2>&1
    rm -rf /tmp/infers > /dev/null 2>&1
    rm -rf /deploybaseagent > /dev/null 2>&1
    rm -rf /etc/uuid > /dev/null 2>&1
    rm -rf /srv/druid/var/druid* > /dev/null 2>&1
    rm -rf /opt/crypt_tmp > /dev/null 2>&1
    rm -rf /opt/redis > /dev/null 2>&1
    rm -rf /opt/zenith > /dev/null 2>&1
    rm -rf /usr/local/bin/ > /dev/null 2>&1
    rm -rf /var/log/cleanlog > /dev/null 2>&1
    rm -rf /var/log/tools > /dev/null 2>&1
    rm -rf /opt/collected_log > /dev/null 2>&1
    rm -rf /opt/FusionInsight_Manager > /dev/null 2>&1
    rm -rf /opt/install_check > /dev/null 2>&1
    rm -rf /opt/proxy_package_dir > /dev/null 2>&1
    rm -rf /var/log/performance > /dev/null 2>&1
    rm -rf /etc/logrotate.d/log_performance > /dev/null 2>&1
    rm -rf /tmp/hadoop-* > /dev/null 2>&1
    rm -rf /tmp/lockfile_* > /dev/null 2>&1
    rm -rf /opt/export_nce_home > /dev/null 2>&1
    rm -rf /opt/pair > /dev/null 2>&1
    rm -rf /export > /dev/null 2>&1

    showLog_info "${LINENO}" "Success to remove CloudSOP file."
}


################################################################################
# Function: clear_startup
# Description: 清理服务启停
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function clear_startup()
{
    chkconfig --del ossipmc > /dev/null 2>&1
    chkconfig --del ossipmc01 > /dev/null 2>&1

    rm -rf /etc/init.d/ossipmc > /dev/null 2>&1
    rm -rf /etc/init.d/ossipmc01 > /dev/null 2>&1
}


################################################################################
# Function: uninstall
# Description: 执行卸载CloudSOP
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function uninstall()
{
    showLog_info "${LINENO}" "Start to uninstall CloudSOP..."
    if [[ ${business_float_ip} == "" ]]; then
        ls ${MCCOMMONSERVICE_PATH} > /dev/null 2>&1
        if [[ $? == 0 ]]; then
            showLog_info "${LINENO}" "the mccommonservice_path exist."
            business_float_ip=$(cat ${MCCOMMONSERVICE_PATH} | grep "ACTIVE_HOST" | awk -F "=" '{print $2}' | awk -F ":" '{print $1}' | head -1 | grep -E ${ipv4_re} || cat ${MCCOMMONSERVICE_PATH} | grep "ACTIVE_HOST" | awk -F "=" '{print $2}' | awk -F ":" '{print $1}' | head -1 | grep -E ${ipv6_re})
        fi
    fi

    if [[ ${lvs_ip} == "" ]]; then
        ls ${SOUTH_ENV_FILE} > /dev/null 2>&1
        if [[ $? == 0 ]]; then
            showLog_info "${LINENO}" "the south_env_file exist."
            lvs_ip=`catch_lvs`
            if [[ $? != 0 ]]; then
                lvs_ip=""
            fi
        fi
    fi
    # 升级完毕后，没有执行回滚，也没执行升级确认，直接卸载的场景会导致安装NdpToolService会失败，需要去锁
    showLog_info "${LINENO}" "Start to delete upgrade protection locks"
    if [[ -f "/export/ossuser/upgrade_dir/upgrade_install.flag" ]];then
        chattr -i /export/ossuser/upgrade_dir/upgrade_install.flag
    fi
    if [[ -f "/export/ossuser/upgrade_dir/upgrade_replace_install.flag" ]];then
        chattr -i /export/ossuser/upgrade_dir/upgrade_replace_install.flag
    fi
    showLog_info "${LINENO}" "end to delete upgrade protection locks"
    uninstall_cloudsop

    showLog_info "${LINENO}" "Manager float ip:${business_float_ip}."
    showLog_info "${LINENO}" "South float ip:${lvs_ip}."

    if [[ ${business_float_ip} != "" ]]; then
         out_netcard=$(ip a | grep ":1$" | awk '{print $NF}' | head -1)
         showLog_info "${LINENO}" "Delete the first manager ip ,the out net card is ${out_netcard}."
         if [[ ${out_netcard} != "" ]]; then
            ifconfig ${out_netcard} down > /dev/null 2>&1
            if [[ -f "sh /usr/local/snbsudobin/RCLVSService/uninstall.sh" ]]; then
                # Kill the Keepalive process.
                sh /usr/local/snbsudobin/RCLVSService/uninstall.sh
            fi

         fi
    fi

    if [[ ${lvs_ip} != "" ]]
    then
        netcard=$(ip a | grep " ${lvs_ip}/" | awk '{print $NF}' | grep -v lo | head -1)
        showLog_info "${LINENO}" "Delete the first south ip ,the net card is ${netcard}."
        if [[ ${netcard} != "" ]];then
            ip addr del ${lvs_ip} dev ${netcard} > /dev/null 2>&1
        fi
        ip addr del ${lvs_ip} dev lo > /dev/null 2>&1
        route del -host ${lvs_ip} > /dev/null 2>&1
    fi
    ifconfig lo:0 down > /dev/null 2>&1

    # 加固，防止keepalive进程拉起lvs浮动IP
    showLog_info "${LINENO}" "Detect keepalive process."
    ps -ef | grep keepalive | grep RCLVSService | grep -v grep
    if [[ $? == 0 ]]; then
        showLog_info "${LINENO}" "Start to kill keepalive process."
        ps -ef | grep keepalive | grep RCLVSService | grep -v grep | awk '{print $2}' | xargs kill -9
    fi
    showLog_info "${LINENO}" "Success to uninstall CloudSOP."

}


################################################################################
# Function: catch_lvs
# Description: 获取产品lvsIP信息
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function catch_lvs()
{
    # 从nodelists.json中获取lvs所在行，从首行到lvs所在行获取最后一个左括号行号，从lvs所在行到尾行获取第一个右括号行号。
    # 从筛选出的{}中的信息截取lvs_IP
    lvs_line=$(grep -n ":lvs" ${SOUTH_ENV_FILE} | head -n 1 | awk -F':' '{print $1}')
    if [[ ! -n "$lvs_line" ]]; then
	    showLog_error "${LINENO}" "Fail to catch LVS IP."
        return 1
    fi
    left_bracket_line=$(sed -n "1,${lvs_line}p" ${SOUTH_ENV_FILE} | grep -n '{' | tail -n 1 | awk -F':' '{print $1}')
    right_bracket_line=$(sed -n "${lvs_line},\$p" ${SOUTH_ENV_FILE} | grep -n '}' | head -n 1 | awk -F':' '{print $1}')
    let right_bracket_line=lvs_line+right_bracket_line-1
    sed -n "${left_bracket_line},${right_bracket_line}p" ${SOUTH_ENV_FILE} | grep '\"IP\"' | awk -F ':' '{print $2}' | awk -F '\"' '{print $2}' | grep -E ${ipv4_re} || sed -n "${left_bracket_line},${right_bracket_line}p" ${SOUTH_ENV_FILE} | grep '\"IP\"' | awk -F ':' '{print $2}' | awk -F '\"' '{print $2}' | grep -E ${ipv6_re}
}


################################################################################
# Function: check
# Description: 检查是否有多余进程
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function check()
{
    ps -ef | egrep "redis|gauss|dbuser|ossdaem|ossuser|nginx|zenith" | grep -v "grep" >/dev/null 2>&1
    reval=$?
    return ${reval}
}


################################################################################
# Function: stopapp
# Description: 停止应用
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function stopapp()
{
    ps -ef | egrep pkgrepo- | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
}


################################################################################
# Function: f_uninstall
# Description: 删除进程
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function f_uninstall()
{
    ps -ef | egrep "/var/log/oss|dbuser|ossdaem|ossuser|nginx" | grep -v "grep" | awk '{print $2}' | xargs kill -9 >/dev/null
    uninstall >/dev/null 2>&1
}


################################################################################
# Function: del_float_ip
# Description: 删除浮动IP
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function del_float_ip()
{
    out_netcard=$(ip a | grep ":1$" | awk '{print $NF}' | head -1)
    showLog_info "${LINENO}" "Delete the manager ip finally ,the out net card is ${out_netcard}."
    if [[ ${out_netcard} != "" ]]
    then
        ifconfig ${out_netcard} down
    fi

    if [[ ${lvs_ip} != "" ]]
    then
        netcard=$(ip a | grep " ${lvs_ip}/" | awk '{print $NF}' | grep -v lo | head -1)
        showLog_info "${LINENO}" "Delete the south ip finally ,the out net card is ${netcard}."
        if [[ ${netcard} != "" ]];then
            ip addr del ${lvs_ip} dev ${netcard}
        fi
        ip addr del ${lvs_ip} dev lo > /dev/null 2>&1
    fi
    ifconfig lo:0 down > /dev/null 2>&1
}


################################################################################
# Function: delete_user
# Description: 删除用户
# Parameter:
#   input:
#   $1:删除用户名
#   output:
#   N/A
# Return: N/A
##################################################################################
function delete_user()
{
    showLog_info "${LINENO}" "Start to delete the user $1."
    cat /etc/passwd | grep -w "$1" >/dev/null
	  if [ $? -ne 0 ]; then
		    syslog "Uninstall" "fi_uninstall.sh" "There is no user named $1."
		    showLog_info "${LINENO}" "There is no user named $1."
	  else
        killall -u $1
        userdel -r -f $1 >/dev/null 2>&1
        if [ $? -eq 0 ]; then
            syslog "Uninstall" "fi_uninstall.sh"  "Success to delete use $1."
            showLog_info "${LINENO}" "Success to delete the user $1."
        else
            syslog "Uninstall" "fi_uninstall.sh"  "Failed to delete use $1, it may effect the installation of next time. Delete the user manually, please!"
            showLog_warn "${LINENO}" "Failed to delete use $1, it may effect the installation of next time. Delete the user manually, please!"
        fi
	  fi
}


################################################################################
# Function: delete_analyzer_user
# Description: 删除分析器用户以及组
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function delete_analyzer_user_except_ossadm()
{
    showLog_info "${LINENO}" "Start to delete user and group."
    delete_user dbuser
    rm -f /etc/sssd/sssd.conf
    rm -fr /var/lib/sss/db/*
    rm -fr /var/lib/sss/mc/*
    rm -f /etc/krb5.conf
    rm -f /tmp/krb5cc_*
    service sssd stop
    service nscd stop
    delete_user ossuser
    groupdel dbgroup >/dev/null 2>&1
    showLog_info "${LINENO}" "Success to delete user and group."
    return 0
}


################################################################################
# Function: post_delete_ossuser
# Description: 加固卸载ossuser
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function post_delete_ossuser()
{
    oper_user=ossuser
    retry_times=5
    sleep 10
    showLog_info "${LINENO}" "Start to check ossuser exist."
    while [[ $(id ${oper_user}) && retry_times -gt 0 ]]
    do
        showLog_info "${LINENO}" "check ossuser status."
        if [[ $(id ${oper_user}) ]];then
          which nscd > /dev/null 2>&1
          if [ $? -eq 0 ]; then
              /usr/sbin/nscd -i group
              /usr/sbin/nscd -i passwd
              service nscd stop
          fi
          rm -f /etc/sssd/sssd.conf
          rm -rf /var/lib/sss/db/*
          service sssd stop
          rm -rf /var/lib/sss/db/*
          service sssd restart
          sleep 20
          retry_times=${retry_times}-1
        else
          break
        fi
    done
    showLog_info "${LINENO}" "Success to check ossuser exist."
    return 0
}


################################################################################
# Function: restore_ip4_tables
# Description: 恢复IPV4防火墙规则
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function restore_ip4_tables()
{
    showLog_info "${LINENO}" "Start to clear iptables."

    iptables -L -n 2>/dev/null | grep ${oss_firewall} > /dev/null 2>&1
    [ $? -ne 0 ] && return 0
    if [ $is_euler = true ];then
        iptables -w -D INPUT -j ${oss_firewall} > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -w -D INPUT -j ${oss_firewall}"
        iptables -w -F ${oss_firewall}  > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -w -F ${oss_firewall}"
        iptables -w -X ${oss_firewall} > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -w -X ${oss_firewall}"
    else
        iptables -D INPUT -j ${oss_firewall} > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -D INPUT -j ${oss_firewall}"
        iptables -F ${oss_firewall}  > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -F ${oss_firewall}"
        iptables -X ${oss_firewall} > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:iptables -X ${oss_firewall}"
    fi

    if [ $is_suse12 = true -o $is_euler = true ]; then
        systemctl disable ossportfilter_${product_name}.service > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:systemctl disable ossportfilter_${product_name}.service"
        rm -f "/etc/systemd/system/ossportfilter_${product_name}.service" > /dev/null 2>&1
        systemctl daemon-reload > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:systemctl daemon-reload"
    else
        /sbin/insserv -r $autustart_file_name > /dev/null 2>&1 || echo "failed to do iptables clean,cmd:insserv -r ${autustart_file_name}"
    fi
    [ -f $autustart_file_name ] && rm -f $autustart_file_name > /dev/null 2>&1
    [ -f $oss_rule_file ] && rm -f $oss_rule_file > /dev/null 2>&1
    iptables -L INPUT -n | egrep "ACCEPT\s+tcp.*0\.0\.0\.0/0\s+tcp\s+dpts:26200:26299" | awk '{print $4}' | xargs -I {} iptables -D INPUT -s {} -p tcp --dport 26200:26299 -j ACCEPT
    iptables -D INPUT -p tcp --dport 26200:26299 -j DROP

    showLog_info "${LINENO}" "Success to clear iptables."
    return 0
}


################################################################################
# Function: db_reinforcement_rollback
# Description: 数据库加固回滚
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function db_reinforcement_rollback(){
    is_suse12=false
    is_euler=false
    suse_version=`cat /etc/os-release-uniep 2> /dev/null | grep -v "#" | grep VERSION | awk '{print $3}'`
    if [ "$suse_version" != "" ];then
        if [[ "$suse_version" =~ ^[0-9]+$ ]];then
            if [ $suse_version -ge 12 ];then
                is_suse12=true
            fi
        fi
    fi
    release_file="/etc/os-release"
    if [ -f $release_file ];
    then
        grep "EulerOS" $release_file > /dev/null 2>&1
        [ $? -eq 0 ] && is_euler=true
    fi

    product_path="/opt/oss/manager/var/tenants"
    mkdir -p ${product_path}/product
    if [ -d ${product_path} ];
    then
        for file in `ls ${product_path}`
        do
          product_name=${file}
          oss_firewall="oss_firewall_${product_name}"
          autustart_file_ipv6_name="/etc/init.d/OSS_CUSTOMPORT_IPV6_${product_name}"
          oss_rule_file="/etc/oss_iprule_${product_name}.conf"
          restore_ip4_tables
          if [[ $? != 0 ]]
          then
              showLog_error "${LINENO}" "Fail to rollback database reinforcement."
              exit 1
          fi
        done
    fi
    service iptables save
}


################################################################################
# Function: clean_sudobin
# Description: 清理sudobin
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function clean_sudobin(){
    rm -rf /etc/oss_sudoers
    rm -rf /etc/uniep_sudoers
    rm -rf /etc/sudoers.d/oss_esight_sudoers
    sed "/oss_sudoers/d" /etc/sudoers > /etc/sudoers.bak;mv -f /etc/sudoers.bak /etc/sudoers
    sed "/uniep_sudoers/d" /etc/sudoers > /etc/sudoers.bak;mv -f /etc/sudoers.bak /etc/sudoers
    sed "/ossadm/d" /etc/sudoers > /etc/sudoers.bak;mv -f /etc/sudoers.bak /etc/sudoers
}


################################################################################
# Function: clean_spark
# Description: 清理Spark
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function clean_spark()
{
    if [[ -f "/usr/local/insight/bin/clean_spark_usercache.sh" ]];then
        bash /usr/local/insight/bin/clean_spark_usercache.sh uninstall
        rm -rf /usr/local/insight
    fi

}


################################################################################
# Function: del_remain_lo
# Description: 删除残留的回环IP
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function del_remain_lo(){
    lo_ip_list=$(ip a show lo | grep ' inet ' | awk  '{print $2}' | awk -F "/" '{print $1}' | grep -v '^127')
    if [[ $? == 0 ]]
    then
        for lo_ip in ${lo_ip_list}
            do
                ip addr del ${lo_ip} dev lo > /dev/null 2>&1
            done
    fi
}


################################################################################
# Function: clean_ip6tables_rule
# Description: 清除IPV6防火墙规则
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function clean_ip6tables_rule()
{
    if [[ -f "/etc/sysconfig/ip6tables_insight" ]]; then
        rm -rf /etc/sysconfig/ip6tables_insight
    fi
    cat /etc/rc.local | grep "ip6tables_insight"  > /dev/null 2>&1
    if [[ $? -eq 0 ]]; then
        sed "/.*ip6tables_insight.*/d" /etc/rc.local > /etc/rc.local.bak;mv -f /etc/rc.local.bak /etc/rc.local
        sed "/.*OSS_CUSTOMPORT_IPV6.*/d" /etc/rc.local > /etc/rc.local.bak;mv -f /etc/rc.local.bak /etc/rc.local
    fi
    ip6tables -F > /dev/null 2>&1
}


################################################################################
# Function: clean_cron_log_collect
# Description: 清除定时任务
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function clean_cron_log_collect()
{
    showLog_info "${LINENO}" "Start to clear crontab for log collect."
    crontab -l | grep -v "log_collect.sh" > tmp_conf ; crontab tmp_conf ; rm -f tmp_conf
    showLog_info "${LINENO}" "Success to clear crontab for log collect."
}


################################################################################
# Function: umount_dir
# Description: ж��vg_appdata����
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function umount_dir()
{
    local i
    dir_list=(`df -h | grep lv_appdata | awk '{print $6}' | sort -r`)
    len=${#dir_list[@]}
    for  ((i=0; i<len; i++))
    do
        showLog_info "${LINENO}" "Start to umount ${dir_list[$i]}."
        kill_process ${dir_list[$i]}
        umount ${dir_list[$i]}
		if [ $? -ne 0 ];then
		    kill_process ${dir_list[$i]}
		    fuser -m -k ${dir_list[$i]}
		    umount ${dir_list[$i]}
		fi
    done
}
################################################################################
# Function: kill_process
# Description:
# Parameter:
# Return: N/A
##################################################################################
function kill_process() {
	lsof $1 | awk '{print $2}' | xargs kill -9 >/dev/null 2>&1
}

################################################################################
# Function: delete_vg
# Description: ɾ��VG
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function delete_vg()
{
    local i
    vg_list=(`vgdisplay | grep 'VG Name' | grep appdata | awk '{print $3}'`)
    len=${#vg_list[@]}
    for  ((i=0; i<len; i++))
    do
        showLog_info "${LINENO}" "Start to remove ${vg_list[$i]}."
        vgremove -f ${vg_list[$i]} > /dev/null 2>&1
    done
}


function delete_lv_appdata()
{
  # 由于工作站场景允许单磁盘安装，需要卸载时候删除vg_root下挂载的相关的lv_appdata
    local i
    lv_appdata_list=(`lvdisplay | grep 'LV Path' | grep appdata | awk '{print $3}'`)
    len=${#lv_appdata_list[@]}
    for  ((i=0; i<len; i++))
    do
        showLog_info "${LINENO}" "Start to remove ${lv_appdata_list[$i]}."
        lvremove -f ${lv_appdata_list[$i]} > /dev/null 2>&1
    done
}


################################################################################
# Function: delete_vol
# Description: ɾ������
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function delete_vol()
{
    showLog_info "${LINENO}" "Start to delete volume."
    export LVM_SUPPRESS_FD_WARNINGS=1
    umount_dir
    delete_vg
    delete_lv_appdata
    sed -i '/lv_appdata/d' /etc/fstab
    rm -rf /opt/fi_install
    mount -a
    rm -rf /dev/vg_appdata
    rm -rf /srv/* > /dev/null 2>&1
}


################################################################################
# Function: main
# Description: 主函数
# Parameter:
#   input:
#   N/A
#   output:
#   N/A
# Return: N/A
##################################################################################
function main()
{
    syslog "Uninstall" "analyzer_uninstall.sh"  "analyzer_uninstall.sh $* begin."
    showLog_info "${LINENO}" "Start to uninstall Analyzer."
    db_reinforcement_rollback
    clean_ip6tables_rule
    stopapp
    uninstall
    rm_path
    clear_startup
    f_uninstall
    delete_analyzer_user_except_ossadm || return 1
    del_float_ip
    del_remain_lo
    clean_sudobin
    clean_spark
    clean_cron_log_collect
    delete_vol
    post_delete_ossuser
    syslog "Uninstall" "analyzer_uninstall.sh" "analyzer_uninstall.sh $* end."
    showLog_info "${LINENO}" "Success to uninstall Analyzer."
    return 0
}

main "$@"
exit $?
