#!/bin/bash

# 检查是否以root用户运行
if [ $(id -u) -ne 0 ]; then
    echo "此脚本需要以root用户身份运行"
    exit 1
fi

clear
echo "================================================"
echo "           小逢智能脚本运行助手v1.1         "
echo "================================================"

# 切换到/root目录
cd /root

# 保存原始脚本路径
script_path="$0"

# 先检查SaoPanel相关文件是否存在再删除
if [ -e "/root/SaoPanel.*" ]; then
    rm -rf /root/SaoPanel.*
fi

# 脚本执行完再删除自身
trap 'rm -rf "$script_path"; exit' EXIT

# 检查是否存在ip_response.txt文件
if [ -f "ip_response.txt" ]; then
    # 文件存在，先删除再访问接口
    rm "ip_response.txt"
    response=$(curl -s "https://qifu-api.baidubce.com/ip/local/geo/v1/district")
    echo "$response" > /root/ip_response.txt
else
    # 文件不存在，直接访问接口
    response=$(curl -s "https://qifu-api.baidubce.com/ip/local/geo/v1/district")
    echo "$response" > /root/ip_response.txt
fi

# 从文件中提取各项信息
ip=$(echo "$response" | grep -oE '"ip":"([^"]*)"' | sed -r 's/"ip":"([^"]*)"/\1/')
country=$(echo "$response" | grep -oE '"country":"([^"]*)"' | sed -r 's/"country":"([^"]*)"/\1/')
# 检查是否成功提取到IP
if [ -z "$ip" ]; then
    echo "无法获取服务器信息，请检查服务器防火墙或联系客服。"
    exit 1
fi

# 显示各项信息
echo "IP地址: $ip"
echo "所在国家: $country"
echo "================================================"

# 添加提示信息
echo "请查看服务器信息是否正确？(y/n)"
read confirmation
if [ "$confirmation" = "y" ]; then
    #!/bin/sh
###
# #Author SaoPig
# #LastAuthor SaoPig
# #since 2022-09-16 15:23:05 +0800
# #lastTime 2022-09-28 17:43:12 +0800
# #message file content
# #文件相对于项目的路径 SaoPanel.sh
# SaoPig
###
clear
cd /root
rm -rf $0
rm -rf /root/SaoPanel.*
rm -rf /root/xsaoml.*
ulimit -c 0
echo "================================================"
echo "           欢迎使用XFengCloud脚本运行助手         "
echo "================================================"
echo
echo -e "\033[31m 1.安装SaoPanel \033[0m"
echo
echo -e "\033[33m 2.安装x-ui面板 \033[0m"
echo
echo -e "\033[32m 3.安装SaoML8.0 \033[0m"
echo
echo -e "\033[33m 4.安装阿里云yum \033[0m"
echo
echo -e "\033[34m 5.安装wget工具 \033[0m"
echo
echo -e "\033[35m 6.更新系统软件包 \033[0m"
echo
echo -e "\033[36m 7.安装BBRplus内核 \033[0m"
echo
echo -e "\033[37m 8.启用BBRplus加速 \033[0m"
echo
echo -e "\033[38m 9.修改服务器DNS \033[0m"
echo
echo -e "\033[39m 10.安装云服务器监控 \033[0m"
echo
echo -e "\033[99m 0.退出脚本运行助手 \033[0m"
echo
read -p "请输入数字并回车:" num
case "$num" in

1)
    clear
	echo "================================================"
	echo "                安装SaoPanel                   "
	echo "================================================"
        rm -rf /bin/saopanel >/dev/null 2>&1
        echo -e "获取资源中..."
        wget -q -O /bin/saopanel http://oss.xiaofeng.host/shouquan/saopanel || {
            echo "获取资源失败，请先安装阿里云yum，再安装wget工具，再次尝试，如果还是不行请联系客服。"
            exit 1
        }
        chmod 777 /bin/saopanel
        saopanel
        exit
    ;;

2)
    clear
	echo "================================================"
	echo "               安装X-ui面板            "
	echo "================================================"
    rm -rf /bin/xsaoml >/dev/null 2>&1
        echo -e "获取资源中..."
        wget -q -O /bin/xsaoml http://oss.xiaofeng.host/shouquan/install || {
            echo "获取资源失败，请先安装阿里云yum，再安装wget工具，再次尝试，如果还是不行请联系客服。"
            exit 1
        }
        chmod 777 /bin/xsaoml
        xsaoml
        exit
	;;

3)
    clear
	echo "================================================"
	echo "               安装SaoML8.0            "
	echo "================================================"
    rm -rf /bin/xsaoml >/dev/null 2>&1
        echo -e "获取资源中..."
        wget -q -O /bin/xsaoml http://oss.xiaofeng.host/shouquan/xsaoml || {
            echo "获取资源失败，请先安装阿里云yum，再安装wget工具，再次尝试，如果还是不行请联系客服。"
            exit 1
        }
        chmod 777 /bin/xsaoml
        xsaoml
        exit
	;;
  
4)
    clear
	echo "================================================"
	echo "                 安装阿里云yum                  "
	echo "================================================"
    echo "正在下载阿里云CentOS7源..."
    curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    if [ $? -eq 0 ]; then
       echo "阿里云 CentOS 7 源下载成功。"
    # 添加安装 yum-cron 的操作
    sudo yum -y -q install yum-cron
    if [ $? -eq 0 ]; then
       echo "yum-cron 安装成功。"
    else
       echo "yum-cron 安装失败。"
    fi
    # 执行清理命令
    sudo yum clean all
    if [ $? -eq 0 ]; then
        echo "yum 清理完成。"
    else
        echo "yum 清理失败。"
    fi
    # 执行生成缓存命令
    sudo yum makecache
    if [ $? -eq 0 ]; then
        echo "yum 缓存生成成功。"
    else
        echo "yum 缓存生成失败。"
    fi
    else
    echo "阿里云 CentOS 7 源下载失败。"
    fi
    ;;

5)
    clear
	echo "================================================"
	echo "                安装wget工具                   "
	echo "================================================"
    # 执行安装
echo "正在安装 wget 工具..."
sudo yum install -y wget >/dev/null 2>&1 &
pid=$!
i=0
animation_char="/-\|"
animation_index=0
start_time=$(date +%s)
while kill -0 $pid 2>/dev/null; do
    if (( i < 99 )); then
        echo -ne "安装进度：[${i}%] [${animation_char:$animation_index:1}]\r"
        ((i = i + 1))
        ((animation_index = (animation_index + 1) % 4))
    else
        echo -ne "安装进度：[99%] [${animation_char:$animation_index:1}]\r"
        ((animation_index = (animation_index + 1) % 4))
    fi
    elapsed_time=$(($(date +%s) - start_time))
    if (( elapsed_time > 0 )); then
        estimated_total_time=$((elapsed_time * 100 / i))
        remaining_time=$((estimated_total_time - elapsed_time))
        echo -ne "安装进度：[${i}%] (预计剩余时间：$(($remaining_time / 60))m$(($remaining_time % 60))s)[${animation_char:$animation_index:1}]\r"
    fi
    sleep 1
done
wait $pid
if [ $? -eq 0 ]; then
    echo -ne "安装进度：[100%] [安装成功]\r\n"
    echo "wget 安装完成。"
else
    echo -ne "安装进度：[安装失败] [错误信息：$(sudo yum history info | grep 'Error:')]\r\n"
    echo "wget 安装失败。"
fi
	;;

6)
    clear
	echo "================================================"
	echo "                 更新系统软件包                  "
	echo "================================================"
	# 执行更新
	echo "正在更新系统软件包..."
sudo yum update -y >/dev/null 2>&1 &
pid=$!
i=0
animation_char="/-\|"
animation_index=0
start_time=$(date +%s)
while kill -0 $pid 2>/dev/null; do
    if (( i < 99 )); then
        echo -ne "更新进度：[${i}%] [${animation_char:$animation_index:1}]\r"
        ((i = i + 1))
        ((animation_index = (animation_index + 1) % 4))
    else
        echo -ne "更新进度：[99%] [${animation_char:$animation_index:1}]\r"
        ((animation_index = (animation_index + 1) % 4))
    fi
    elapsed_time=$(($(date +%s) - start_time))
    if (( elapsed_time > 0 )); then
        estimated_total_time=$((elapsed_time * 100 / i))
        remaining_time=$((estimated_total_time - elapsed_time))
        echo -ne "更新进度：[${i}%] (预计剩余时间：$(($remaining_time / 60))m$(($remaining_time % 60))s)[${animation_char:$animation_index:1}]\r"
    fi
    sleep 1
done
wait $pid
if [ $? -eq 0 ]; then
    echo -ne "更新进度：[100%] [更新成功]\r\n"
    echo "软件包更新完成。"
else
    echo -ne "更新进度：[更新失败] [错误信息：$(sudo yum history info | grep 'Error:')]\r\n"
    echo "软件包更新失败。"
fi
	;;

7)
    clear
	echo "================================================"
	echo "                安装BBRplus内核                   "
	echo "================================================"
# 下载内核安装包
# 检查 /root/ 目录下是否有 kernel-4.14.129-bbrplus.rpm 文件
# 检查安装包是否存在
if [ -f /root/kernel-4.14.129-bbrplus.rpm ]; then
    echo "BBRplus内核安装包已存在，无需下载。"
else
    echo "正在下载内核安装包..."
    curl -o /root/kernel-4.14.129-bbrplus.rpm http://oss.xiaofeng.host/saopanel/BBRPlus/kernel-4.14.129-bbrplus.rpm >/dev/null 2>&1 &
    pid=$!
    i=0
    animation_char="/-\|"
    animation_index=0
    start_time=$(date +%s)
    while kill -0 $pid 2>/dev/null; do
        if (( i < 99 )); then
            echo -ne "下载进度：[${i}%] [${animation_char:$animation_index:1}]\r"
            ((i = i + 1))
            ((animation_index = (animation_index + 1) % 4))
        else
            echo -ne "下载进度：[99%] [${animation_char:$animation_index:1}]\r"
            ((animation_index = (animation_index + 1) % 4))
        fi
        elapsed_time=$(($(date +%s) - start_time))
        if (( elapsed_time > 0 )); then
            estimated_total_time=$((elapsed_time * 100 / i))
            remaining_time=$((estimated_total_time - elapsed_time))
            echo -ne "下载进度：[${i}%] (预计剩余时间：$(($remaining_time / 60))m$(($remaining_time % 60))s)[${animation_char:$animation_index:1}]\r"
        fi
        sleep 1
    done
    wait $pid
    if [ $? -eq 0 ]; then
        echo -ne "下载进度：[100%] [下载成功]\r\n"
        echo "BBRplus内核安装包下载成功。"
    else
        echo -ne "下载进度：[下载失败] [错误信息：$(curl --help | grep 'Error:')]\r\n"
        echo "BBRplus内核安装包下载失败。"
    fi
fi

# 安装内核
echo "正在安装 BBRplus 内核..."
sudo yum install -y kernel-4.14.129-bbrplus.rpm >/dev/null 2>&1 &
pid=$!
i=0
animation_char="/-\|"
animation_index=0
start_time=$(date +%s)
while kill -0 $pid 2>/dev/null; do
    if (( i < 99 )); then
        echo -ne "安装进度：[${i}%] [${animation_char:$animation_index:1}]\r"
        ((i = i + 1))
        ((animation_index = (animation_index + 1) % 4))
    else
        echo -ne "安装进度：[99%] [${animation_char:$animation_index:1}]\r"
        ((animation_index = (animation_index + 1) % 4))
    fi
    elapsed_time=$(($(date +%s) - start_time))
    if (( elapsed_time > 0 )); then
        estimated_total_time=$((elapsed_time * 100 / i))
        remaining_time=$((estimated_total_time - elapsed_time))
        echo -ne "安装进度：[${i}%] (预计剩余时间：$(($remaining_time / 60))m$(($remaining_time % 60))s)[${animation_char:$animation_index:1}]\r"
    fi
    sleep 1
done
wait $pid
if [ $? -eq 0 ]; then
    echo -ne "安装进度：[100%] [安装成功]\r\n"
    echo "BBRplus 内核安装成功。"
else
    echo -ne "安装进度：[安装失败] [错误信息：已经存在BBRPlus内核')]\r\n"
    echo "BBRplus 内核安装失败。"
fi

# 设置默认内核
echo "设置 BBRplus 为默认内核..."
grub2-set-default 'CentOS Linux (4.14.129-bbrplus) 7 (Core)'
if [ $? -eq 0 ]; then
    echo -ne "设置进度：[100%] [设置成功]\r\n"
    echo "设置 BBRplus 为默认内核成功。"
    read -p "内核设置成功，是否重启服务器生效？（请输入数字然后点击回车键确定！1：重启服务器，2：退出脚本） " choice
    if [ "$choice" = "1" ]; then
        echo "服务器即将重启服务器..."
        reboot
    elif [ "$choice" = "2" ]; then
        echo "退出脚本。"
        exit 0
    else
        echo "无效选择。"
    fi
else
    echo -ne "设置进度：[设置失败] [错误信息：$(grub2-set-default --help | grep 'Error:')]\r\n"
    echo "设置 BBRplus 为默认内核失败。"
fi
;;

8)
    clear
	echo "================================================"
	echo "                启用BBRplus加速                   "
	echo "================================================"
# 添加网络参数配置
# 检查 /etc/sysctl.conf 文件是否存在
if [ -f /etc/sysctl.conf ]; then
    echo "/etc/sysctl.conf 文件已存在，检查是否已有特定网络参数配置。"
# 检查是否有 net.core.default_qdisc=fq
    grep -q "net.core.default_qdisc=fq" /etc/sysctl.conf
    if [ $? -ne 0 ]; then
        echo "未找到 net.core.default_qdisc=fq，添加该配置。"
        echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
    else
        echo "net.core.default_qdisc=fq 配置已存在，无需添加。"
    fi
# 检查是否有 net.ipv4.tcp_congestion_control=bbrplus
    grep -q "net.ipv4.tcp_congestion_control=bbrplus" /etc/sysctl.conf
    if [ $? -ne 0 ]; then
        echo "未找到 net.ipv4.tcp_congestion_control=bbrplus，添加该配置。"
        echo "net.ipv4.tcp_congestion_control=bbrplus" >> /etc/sysctl.conf
    else
        echo "net.ipv4.tcp_congestion_control=bbrplus 配置已存在，无需添加。"
    fi
    if [ $? -eq 0 ]; then
        echo "网络参数配置检查和添加成功。"
    else
        echo "网络参数配置检查和添加失败。"
    fi
    else
    echo "/etc/sysctl.conf 文件不存在，先创建文件再添加网络参数配置。"
    touch /etc/sysctl.conf
    echo "net.core.default_qdisc=fq" >> /etc/sysctl.conf
    echo "net.ipv4.tcp_congestion_control=bbrplus" >> /etc/sysctl.conf
    if [ $? -eq 0 ]; then
        echo "网络参数配置添加成功。"
    else
        echo "网络参数配置添加失败。"
    fi
    fi
# 使配置生效
    sysctl -p

# 检查 BBRPlus 是否启用成功
lsmod | grep bbrplus
if [ $? -eq 0 ]; then
    echo "BBRplus 已成功启用。"
else
    echo "BBRplus 启用失败。"
fi
;;

9)
    clear
	echo "================================================"
	echo "               欢迎使用DNS修改助手               "
	echo "================================================"
	echo
	echo "  1 - 修改为阿里云DNS（推荐）"
	echo "      提示：223.5.5.5-223.6.6.6"
	echo
	echo "  2 - 修改为腾讯云DNS"
	echo "      提示 183.60.83.19-183.60.82.98"
	echo
	echo "  3 - 修改为114 DNS（推荐）"
	echo "      提示：114.114.114.114-114.114.115.115"
	echo
	echo "  4 - 修改为DNS 派"
	echo "      提示：101.226.4.6-218.30.118.6"
	echo
	echo -n "请输入选项并回车："
	read dns
	if [[ $dns == 1 ]]; then
		echo 'nameserver 223.5.5.5
nameserver 223.6.6.6' >/etc/resolv.conf
		echo "OK!"
		exit 0
	fi
	if [[ $dns == 2 ]]; then
		echo 'nameserver 183.60.83.19
nameserver 183.60.82.98' >/etc/resolv.conf
		echo "OK!"
		exit 0
	fi
	if [[ $dns == 3 ]]; then
		echo 'nameserver 114.114.114.114
nameserver 114.114.115.115' >/etc/resolv.conf
		echo "OK!"
		exit 0
	fi
	if [[ $dns == 4 ]]; then
		echo 'nameserver 101.226.4.6
nameserver 218.30.118.6' >/etc/resolv.conf
		echo "OK!"
		exit 0
	fi
	;;

10)

# 安装云服务器监控系统
clear
echo "================================================"
echo "               安装云服务器监控系统              "
echo "================================================"

# 检查安装包是否存在
if [ -f "/root/cloudmonitor.zip" ]; then
    echo "服务器监控系统安装包已存在，无需下载。"
    # 安装包存在时直接执行下载完成后的操作
    yum -y install unzip
    unzip -o cloudmonitor
    rm -rf /root/cloudmonitor
    chmod 777 status.sh
    bash status.sh
else
    # 下载安装包
    echo "正在下载服务器监控系统安装包..."
    download_pid=$!
    animation_chars="/-\|"
    animation_index=0
    start_time=$(date +%s)

    # 使用 wget 进行下载
    wget -O /root/cloudmonitor.zip http://oss.xiaofeng.host/cloudmonitor/cloudmonitor.zip &
    download_pid=$!

    while kill -0 $download_pid 2>/dev/null; do
        echo -ne "下载进度： [${animation_chars:$animation_index:1}]\r"
        ((animation_index = (animation_index + 1) % 4))
        sleep 1
    done

    wait $download_pid

    if [ $? -eq 0 ]; then
        echo -ne "下载进度： [下载成功]\r\n"
        echo "服务器监控系统安装包下载成功。"

        # 安装包下载完成后执行的操作
        yum -y install unzip
        unzip -o cloudmonitor
        rm -rf /root/cloudmonitor
        chmod 777 status.sh
        bash status.sh
    else
        error_msg=$(wget -q --spider http://oss.xiaofeng.host/cloudmonitor/cloudmonitor.zip 2>&1 | grep -i "error")
        if [ -z "$error_msg" ]; then
            error_msg="未知错误"
        fi
        echo -ne "下载进度： [下载失败] [错误信息：$error_msg]\r\n"
        echo "服务器监控系统安装包下载失败。请检查网络连接或稍后重试。"
        exit 1
    fi
fi
;;

0)
	echo -e "脚本已退出"
	exit
	;;
*)
	echo -e "请输入正确数字"
	;;
esac
else
    echo "操作已取消。"
    exit 0
fi