#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8

Font_Yellow='\033[1;33m'
Font_Suffix='\033[0m'

if [ ! -d /www/server/panel/BTPanel ];then
	echo "============================================="
	echo "错误, 5.x不可以使用此命令升级!"
	echo "5.9平滑升级到6.0的命令：curl http://io.bt.sb/install/update_to_6.sh|bash"
	exit 0;
fi

if [ ! -f "/www/server/panel/pyenv/bin/python3" ];then
	echo "============================================="
	echo "错误, 当前面板过旧/py-2.7/无pyenv环境，无法升级至最新版面板"
	echo "请截图 联系 TG群组：@rsakuras 或者 QQ群组：1042692095 求助！"
	exit 0;
fi

if [ -f "/etc/redhat-release" ];then
	Centos6Check=$(cat /etc/redhat-release | grep ' 6.' | grep -iE 'centos|Red Hat')
	if [ "${Centos6Check}" ];then
		echo "Centos6不支持升级宝塔面板，建议备份数据重装更换Centos7/8安装宝塔面板"
		exit 1
	fi 
	Centos8Check=$(cat /etc/redhat-release | grep ' 8.' | grep -iE 'centos|Red Hat')
	if [ "${Centos8Check}" ];then
		if [ ! -f "/usr/bin/python" ] && [ -f "/usr/bin/python3" ] && [ ! -d "/www/server/panel/pyenv" ]; then
			ln -sf /usr/bin/python3 /usr/bin/python
		fi
	fi
fi

# public_file=/www/server/panel/install/public.sh
# publicFileMd5=$(md5sum ${public_file} 2>/dev/null|awk '{print $1}')
# md5check="acfc18417ee58c64ff99d186f855e3e1"
# if [ "${publicFileMd5}" != "${md5check}"  ]; then
# 	wget -O Tpublic.sh http://download.bt.cn/install/public.sh -T 2 -t 1;
# 	publicFileMd5=$(md5sum Tpublic.sh 2>/dev/null|awk '{print $1}')
# 	if [ "${publicFileMd5}" == "${md5check}"  ]; then
# 		\cp -rpa Tpublic.sh $public_file
# 	fi
# 	rm -f Tpublic.sh
# fi
# . $public_file
#download_Url=$NODE_URL

mypip="pip"
env_path=/www/server/panel/pyenv/bin/activate
if [ -f $env_path ];then
	mypip="/www/server/panel/pyenv/bin/pip"
fi

if [ -f "/www/server/panel/data/down_url.pl" ];then
	D_NODE_URL=$(cat /www/server/panel/data/down_url.pl|grep bt.cn)
fi

if [ -z "${D_NODE_URL}" ];then
	D_NODE_URL="download.bt.cn"
fi

download_Url=$D_NODE_URL
downloads_Url=http://io.bt.sb


Set_Centos7_Repo(){
    if [ -f "/etc/yum.repos.d/docker-ce.repo" ];then
        mv /etc/yum.repos.d/docker-ce.repo /etc/yum.repos.d/docker-ce.repo_backup
    fi
	MIRROR_CHECK=$(cat /etc/yum.repos.d/CentOS-Base.repo |grep "[^#]mirror.centos.org")
	if [ "${MIRROR_CHECK}" ] && [ "${is64bit}" == "64" ];then
		\cp -rpa /etc/yum.repos.d/ /etc/yumBak
		sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
	fi

	TSU_MIRROR_CHECK=$(cat /etc/yum.repos.d/CentOS-Base.repo |grep "tuna.tsinghua.edu.cn")
	if [ "${TSU_MIRROR_CHECK}" ];then
		\cp -rpa /etc/yum.repos.d/ /etc/yumBak
		sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=https://mirrors.tuna.tsinghua.edu.cn|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
		sed -i 's|#baseurl=http://mirrors.tuna.tsinghua.edu.cn|baseurl=http://vault.epel.cloud|g' /etc/yum.repos.d/CentOS-*.repo
	fi
	
	ALI_CLOUD_CHECK=$(grep Alibaba /etc/motd)
	Tencent_Cloud=$(cat /etc/hostname |grep -E VM-[0-9]+-[0-9]+)
	if [ "${ALI_CLOUD_CHECK}" ] || [ "${Tencent_Cloud}" ];then
		return
	fi
	
	yum install tree -y
	if [ "$?" != "0" ] ;then
		TAR_CHECK=$(which tree)
		if [ "$?" == "0" ] ;then
			\cp -rpa /etc/yum.repos.d/ /etc/yumBak
			if [ -z "${download_Url}" ];then
				download_Url="http://download.bt.cn"
			fi
			curl -Ss --connect-timeout 5 -m 60 -O ${download_Url}/src/el7repo.tar.gz
			rm -f /etc/yum.repos.d/*.repo
			tar -xvzf el7repo.tar.gz -C /etc/yum.repos.d/
		fi
	fi

	yum install tree -y
	if [ "$?" != "0" ] ;then
		sed -i "s/vault.epel.cloud/mirrors.cloud.tencent.com/g" /etc/yum.repos.d/*.repo
	fi
}
if [ -f "/etc/redhat-release" ];then
	Centos7Check=$(cat /etc/redhat-release | grep ' 7.' | grep -iE 'centos|Red Hat')
	if [ "${Centos7Check}" ];then
		Set_Centos7_Repo
	fi
fi

wget -O fix_install.sh $download_Url/tools/fix_install.sh
nohup bash fix_install.sh > /www/server/panel/install/fix.log 2>&1 &

setup_path=/www
if [ -f "/www/server/panel/data/node_url.pl" ] && [ -f "/usr/bin/jq" ];then
	#WWW_NODE=$(cat /www/server/panel/data/node_url.pl|jq -r '.["www-node"].url')
	version=$(curl -Ss --connect-timeout 12 -m 2 https://lts.bt.sb/api/panel/get_version)
fi
VERSION_CHECK=$(echo $version | grep -E '^9\.0\.0$|^10\.0\.[0-9]+$')
if [ -z "$VERSION_CHECK" ];then
	version=$(curl -Ss --connect-timeout 12 -m 2 https://lts.bt.sb/api/panel/get_version)
fi
VERSION_CHECK=$(echo $version | grep -E '^9\.0\.0$|^10\.0\.[0-9]+$')
if [ -z "$VERSION_CHECK" ];then
  version=$(grep "g.version = " /www/server/panel/class/common.py | awk -F"'" '{print $2}')
  if [ -z "$version" ];then
    version='10.0.2'
  fi
fi
armCheck=$(uname -m|grep arm)
if [ "${armCheck}" ];then
	version='10.0.2'
fi

if [ "$1" ];then
	version=$1
fi

if [ "$2" ];then
	SO_BAK="true"
	/etc/init.d/bt stop
fi

if [ "$SO_BAK" ];then
	mkdir -p /www/server/panelso
	\cp -rpa /www/server/panel/class/*.so /www/server/panelso
fi


TLS_CHECK=$(grep get_stable_panel /www/server/panel/class/system.py)
if [ -z "${TLS_CHECK}" ];then
    wget -T 20 -O /tmp/panel.zip $downloads_Url/install/update/LinuxPanelStable-${version}.zip
else
    TLS_VERSION=$(grep "g.version = " /www/server/panel/class/common.py | awk -F"'" '{print $2}')
    wget -T 20 -O /tmp/panel.zip $downloads_Url/install/update/LinuxPanelStable-${TLS_VERSION}.zip
fi

dsize=$(du -b /tmp/panel.zip|awk '{print $1}')
if [ $dsize -lt 10240 ];then
	echo "获取更新包失败，请及时联系 TG群组：@rsakuras 或者 QQ群组：1042692095 进行反馈！"
	exit;
fi

chattr -i /www/server/panel/data/userInfo.json
unzip -o /tmp/panel.zip -d $setup_path/server/ > /dev/null 2>&1
rm -f /tmp/panel.zip
sed -i 's/[0-9\.]\+[ ]\+www.bt.cn//g' /etc/hosts
sed -i 's/[0-9\.]\+[ ]\+api.bt.sb//g' /etc/hosts
if [ "$version" = "11.0.0" ]; then
    echo "检测到指定版本为11.0.0，正在下载新版 softList 配置..."
    wget -O /www/server/panel/data/softList.conf ${download_Url}/install/conf/softListtls10.conf
fi
cd $setup_path/server/panel/
check_bt=`cat /etc/init.d/bt`
if [ "${check_bt}" = "" ];then
	rm -f /etc/init.d/bt
	wget -O /etc/init.d/bt $download_Url/install/src/bt7.init -T 20
	chmod +x /etc/init.d/bt
fi
echo "=============================================================="
echo "正在修复面板依赖问题"
rm -f /www/server/panel/*.pyc
rm -f /www/server/panel/class/*.pyc
#pip install flask_sqlalchemy
#pip install itsdangerous==0.24

if [ -f "/www/server/panel/pyenv/bin/pip3" ];then
	btpip_path="/www/server/panel/pyenv/bin/pip3"
	FlaskV=$($btpip_path list 2>/dev/null|grep "Flask " |awk '{print $2}'|cut -f 1 -d .)
	piplist_count=$($btpip_path list 2>/dev/null|wc -l)
	if [ "${FlaskV}" -le "2" ] && [ "${piplist_count}" -le "118" ];then
		echo "检测到面板运行环境过老，正常尝试修复面板依赖"
		pyenv_path="/www/server/panel"
		wget -O $pyenv_path/pyenv/pip.txt $download_Url/install/pyenv/pip-3.7.16.txt -T 5
		$pyenv_path/pyenv/bin/pip install -U pip
		$pyenv_path/pyenv/bin/pip install -U setuptools==65.5.0
		$pyenv_path/pyenv/bin/pip install -U wheel==0.34.2 
		$pyenv_path/pyenv/bin/pip install -r $pyenv_path/pyenv/pip.txt
		echo "依赖修复完成，如面板仍无法正常访问，请联系宝塔官方人员进行求助"
	fi

	wget -O pip-packs.txt $download_Url/install/pyenv/pip-packs.txt
	PIP_PACKS=$(cat pip-packs.txt)
	for P_PACK in ${PIP_PACKS};
	do
		btpip show ${P_PACK} > /dev/null 2>&1
		if [ "$?" == "1" ];then
			btpip install ${P_PACK}
		fi 
	done
fi


pip_list=$($mypip list 2>&1)
request_v=$(btpip list 2>/dev/null|grep "requests "|awk '{print $2}'|cut -d '.' -f 2)
if [ "$request_v" = "" ] || [ "${request_v}" -gt "28" ];then
	$mypip install requests==2.27.1
	$mypip install chardet==4.0.0
fi

NATSORT_C=$(echo $pip_list|grep natsort)
if [ -z "${NATSORT_C}" ];then
	btpip install natsort
fi

openssl_v=$(echo "$pip_list"|grep pyOpenSSL)
if [ "$openssl_v" = "" ];then
	$mypip install pyOpenSSL
fi

#cffi_v=$(echo "$pip_list"|grep cffi|grep 1.12.)
#if [ "$cffi_v" = "" ];then
#	$mypip install cffi==1.12.3
#fi

pymysql=$(echo "$pip_list"|grep pymysql)
if [ "$pymysql" = "" ];then
	$mypip install pymysql
fi
GEVENT_V=$(btpip list 2> /dev/null|grep "gevent "|awk '{print $2}'|cut -f 1 -d '.')
if [ "${GEVENT_V}" -le "1" ];then
    /www/server/panel/pyenv/bin/pip3 install -I gevent
fi

BROTLI_C=$(btpip list 2> /dev/null |grep Brotli)
if [ -z "$BROTLI_C" ]; then
    btpip install brotli
fi

PYMYSQL_C=$(btpip list 2> /dev/null |grep PyMySQL)
if [ -z "$PYMYSQL_C" ]; then
    btpip install PyMySQL
fi


PY_CRPYT=$(btpip list 2> /dev/null |grep cryptography|awk '{print $2}'|cut -f 1 -d '.')
if [ "${PY_CRPYT}" -le "10" ];then
    btpip install pyOpenSSL==24.1.0
    btpip install cryptography==42.0.5
fi

PYMYSQL_SSL_CHECK=$(btpython -c "import pymysql" 2>&1|grep "AttributeError: module 'cryptography.hazmat.bindings._rust.openssl'")
if [ "${PYMYSQL_SSL_CHECK}" ];then
    btpip uninstall pyopenssl cryptography -y
    btpip install pyopenssl cryptography
fi

btpip uninstall enum34 -y

GEOIP_C=$(echo $pip_list|grep geoip2)
if [ -z "${GEOIP_C}" ];then
	btpip install geoip2==4.7.0
fi

# PANDAS_C=$(echo $pip_list|grep pandas)
# if [ -z "${PANDAS_C}" ];then
# 	btpip install pandas
# fi

pymysql=$(echo "$pip_list"|grep pycryptodome)
if [ "$pymysql" = "" ];then
	$mypip install pycryptodome
fi
echo "修复面板依赖完成！"
echo "==========================================="
echo ""
RE_UPDATE=$(cat /www/server/panel/data/db/update)
if [ "$RE_UPDATE" -ge "4" ];then
    echo "2" > /www/server/panel/data/db/update
fi

#psutil=$(echo "$pip_list"|grep psutil|awk '{print $2}'|grep '5.7.')
#if [ "$psutil" = "" ];then
#	$mypip install -U psutil
#fi

if [ -d /www/server/panel/class/BTPanel ];then
	rm -rf /www/server/panel/class/BTPanel
fi

if [ "$SO_BAK" ];then
	\cp -rpa /www/server/panelso/*.so /www/server/panel/class
fi

echo "==========================================="
echo "正在更新面板文件..............."
sleep 1
echo "更新完成！"
echo "==========================================="

chattr -i /etc/init.d/bt
chmod +x /etc/init.d/bt

#echo > /www/server/panel/data/bind.pl
rm -rf /www/server/panel/data/bind.pl

rm -rf /www/server/panel/class/pluginAuth.cpython-37m-aarch64-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.cpython-37m-i386-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.cpython-37m-loongarch64-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.cpython-37m-x86_64-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.cpython-310-aarch64-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.cpython-310-x86_64-linux-gnu.so
rm -rf /www/server/panel/class/pluginAuth.so
#rm -rf /www/server/panel/class/pluginAuth.py

rm -rf /www/server/panel/class/libAuth.aarch64.so
rm -rf /www/server/panel/class/libAuth.glibc-2.14.x86_64.so
rm -rf /www/server/panel/class/libAuth.loongarch64.so
rm -rf /www/server/panel/class/libAuth.x86-64.so
rm -rf /www/server/panel/class/libAuth.x86.so

#rm -rf /www/server/panel/class/PluginLoader.aarch64.Python3.7.so
#rm -rf /www/server/panel/class/PluginLoader.i686.Python3.7.so
#rm -rf /www/server/panel/class/PluginLoader.loongarch64.Python3.7.so
#rm -rf /www/server/panel/class/PluginLoader.so
rm -rf /www/server/panel/class/PluginLoader.s390x.Python3.7.so
#rm -rf /www/server/panel/class/PluginLoader.x86_64.glibc214.Python3.7.so
#rm -rf /www/server/panel/class/PluginLoader.x86_64.Python3.7.so

#echo "====================================="
rm -f /dev/shm/bt_sql_tips.pl
kill $(ps aux|grep -E "task.pyc|main.py"|grep -v grep|awk '{print $2}')
/etc/init.d/bt start
echo ""
echo 'True' > /www/server/panel/data/restart.pl
pkill -9 gunicorn &
#echo "====================================="

echo -e "\033[1;33m"
echo -e "\033[1;33m=================================="
echo -e "\033[1;33m              赞助商广告"
echo -e "\033[1;33m=================================="
echo ""
    
echo -e "\033[1;36mDreamCloud\033[1;33;1m ★【亚太推荐】★\033[1;36m"
echo -e "日本高防中国优化服务器，低至\$12.75 USD/月，海外 2Tbps+ 中国 100Gbps"
echo -e "https://whmcs.as211392.com/LiteCore-EPYC-NEW?aff=1 "
echo -e "\033[1;33m"
    
echo ""
echo -e "\033[1;35mKURUN CLOUD\033[1;31;1m ★【欧美推荐】★\033[1;35m"
echo -e "美国洛杉矶 CN2GIA+CUPM9929+CMIN2 三网精品回国线路服务器 ★★★ 特价促销中 ★★★  KURUN CLOUD机房直销 最快回国线路 超稳定"
echo -e "https://www.kurun.com/aff/HRZUXBJP"
echo -e "https://t.me/kuruncloud"
echo -e "\033[1;33m"
echo ""
echo -e "\033[31m脚本/官网/群组/频道等广告投放价格：300U /月、2500U /年、5000U /长期\033[1;33m"
echo ""
echo "注意：我们不接受面板插入广告，只接受脚本、群组、频道、论坛官网 等广告投放！"
echo ""
echo -e "需要广告位 转账 TRC20：\033[32mTCYL5ZKJhkXyCNvy3bnbiCHuAa7yKWLDWc\033[1;33m"
echo ""
echo -e "转完之后联系 @pingping_520 发送需要投放的广告内容\033[0m"
echo ""
echo -e "\033[1;33m=================================="
echo -e "\033[0m"

echo -e "\033[36m已成功升级到 [$version]企业版\033[0m";

# 调用接口获取统计信息
response=$(curl -s --connect-timeout 5 --max-time 10 "https://tj.bt.sb/api/count?param=bt&token=6920626369b1f05844f5e3d6f93b5f6e" 2>/dev/null)

# 检查curl请求是否成功
if [ $? -eq 0 ] && [ -n "$response" ]; then
    # 检查 Python 版本
    if command -v python3 &>/dev/null; then
        # 使用 Python 3 解析 JSON
        TodayRunTimes=$(echo "$response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    print(data.get('today_count', 'N/A'))
except (json.JSONDecodeError, KeyError, Exception):
    print('N/A')
" 2>/dev/null)
        TotalRunTimes=$(echo "$response" | python3 -c "
import sys, json
try:
    data = json.load(sys.stdin)
    print(data.get('total_count', 'N/A'))
except (json.JSONDecodeError, KeyError, Exception):
    print('N/A')
" 2>/dev/null)
    elif command -v python &>/dev/null; then
        # 使用 Python 2 解析 JSON
        TodayRunTimes=$(echo "$response" | python -c "
import sys, json
try:
    data = json.load(sys.stdin)
    print data.get('today_count', 'N/A')
except (ValueError, KeyError, Exception):
    print 'N/A'
" 2>/dev/null)
        TotalRunTimes=$(echo "$response" | python -c "
import sys, json
try:
    data = json.load(sys.stdin)
    print data.get('total_count', 'N/A')
except (ValueError, KeyError, Exception):
    print 'N/A'
" 2>/dev/null)
    else
        TodayRunTimes="N/A"
        TotalRunTimes="N/A"
    fi

    if [ "$TodayRunTimes" != "N/A" ] && [ "$TotalRunTimes" != "N/A" ]; then
        echo ""
        echo -e "${Font_Yellow}脚本当天运行次数: ${TodayRunTimes}; 共计运行次数: ${TotalRunTimes} ${Font_Suffix}"
        echo ""
    fi
fi

