#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
pyenv_bin=/www/server/panel/pyenv/bin
rep_path=${pyenv_bin}:$PATH
if [ -d "$pyenv_bin" ];then
	PATH=$rep_path
fi
export PATH
LANG=en_US.UTF-8
cpu_cpunt=$(cat /proc/cpuinfo | grep ^processor | wc -l)
setup_path=/www
is64bit=$(getconf LONG_BIT)
if [ "${is64bit}" != '64' ];then
	echo "Sorry, 32-bit systems are no longer supported and cannot be upgraded.";
	echo "Exit, do nothing"
	exit 1
fi
if [ -f /etc/redhat-release ];then
	Centos6Check=$(cat /etc/redhat-release | grep ' 6.' | grep -iE 'centos|Red Hat')
	if [ "${Centos6Check}" ];then
		echo "Centos6 upgrading is not supported."
		echo "It is recommended to backup the data and reinstall and replace Centos7/8,Ubuntu20/22,Debian11/12 install aaPanel"
		exit 1
	fi 
fi

while [ "$go" != 'y' ] && [ "$go" != 'n' ]; do
    read -p "aaPanel old version is no longer maintained. Do you want to continue? (y/n): " go
done

if [ "$go" == 'n' ]; then
    exit
fi

if [ $(whoami) != "root" ];then
    echo -e "Non-root install, please try the following solutions: \n   1.Please switch to root user \n   2.Try executing the following commands: \n     sudo bash $0 $@"
    exit 1
fi

if [ ! -f "/www/server/panel/BT-Panel" ]; then
	ls -al /www/server/panel/
	echo -e "\033[31m No installation aaPanel. \033[0m"
	exit 1;
fi

up_plugin=0

download_file(){
    dst_file=$1
    tmp_file=/tmp/bt_tmp_file.temp
    if [ -f $tmp_file ];then
        rm -f $tmp_file
    fi
    wget -O ${tmp_file} $2 -T 20
    tmp_size=$(du -b $tmp_file|awk '{print $1}')
    if [ $tmp_size -lt 10 ];then
        echo "|-File download failed $dst_file"
        return
    fi

    if [ -f $dst_file ];then
        rm -f $dst_file
    fi

    mv -f $tmp_file $dst_file

    if [ -f $tmp_file ];then
        rm -f $tmp_file
    fi
}

GetSysInfo() {
	if [ -s "/etc/redhat-release" ]; then
		SYS_VERSION=$(cat /etc/redhat-release)
	elif [ -s "/etc/issue" ]; then
		SYS_VERSION=$(cat /etc/issue)
	fi
	SYS_INFO=$(uname -a)
	SYS_BIT=$(getconf LONG_BIT)
	MEM_TOTAL=$(free -m | grep Mem | awk '{print $2}')
	CPU_INFO=$(getconf _NPROCESSORS_ONLN)

	echo -e ${SYS_VERSION}
	echo -e Bit:${SYS_BIT} Mem:${MEM_TOTAL}M Core:${CPU_INFO}
	echo -e ${SYS_INFO}
	echo -e "Please screenshot the above error message and post to the forum forum.aapanel.com for help"
}

Red_Error(){
	echo '=================================================';
	printf '\033[1;31;40m%b\033[0m\n' "$@";
	GetSysInfo
	exit 1;
}

check_panel(){
    if [ ! -d /www/server/panel/BTPanel ];then
        up_plugin=1
    fi
}

select_node(){
	# public_file=/www/server/panel/install/public.sh
	# if [ ! -f $public_file ];then
	# 	download_file $public_file https://node.aapanel.com/install/public.sh
	# fi

	# publicFileMd5=$(md5sum ${public_file}|awk '{print $1}')
	# md5check="f3fb69f071f7fa800e5f2d5ec3e128c3"
	# if [ "${publicFileMd5}" != "${md5check}"  ]; then
	# 	download_file $public_file https://node.aapanel.com/install/public.sh
	# fi

	# . $public_file

	# download_Url=$NODE_URL

	# if [ "$download_Url" = "" ];then
	# 	download_Url=https://node.aapanel.com
	# fi

	download_Url=https://node.aapanel.com
}

get_version(){
	# version=$(curl -Ss --connect-timeout 12 -m 2 https://brandnew.aapanel.com/api/panel/getLatestOfficialVersion)

	# check_version_num=$( echo "$version"|grep -Eo '^[0-9]+' )
	# if [ "$check_version_num" = '' ];then
	# 	echo "Check version failed!"
	#     version='6.8.37'
	# fi
	
	if [ "$version" = '' ];then
		version='6.8.37'
	fi
}


Install_RPM_Pack() {
    if [ -f "/etc/redhat-release" ] && [ $(cat /etc/os-release|grep PLATFORM_ID|grep -oE "el8") ];then
        yum config-manager --set-enabled powertools
        yum config-manager --set-enabled PowerTools
    fi

    if [ -f "/etc/redhat-release" ] && [ $(cat /etc/os-release|grep PLATFORM_ID|grep -oE "el9") ];then
        dnf config-manager --set-enabled crb -y
    fi

    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    #yum remove -y python-requests python3-requests python-greenlet python3-greenlet
    yumPacks="libcurl-devel wget tar gcc make zip unzip openssl openssl-devel gcc libxml2 libxml2-devel libxslt* zlib zlib-devel libjpeg-devel libpng-devel libwebp libwebp-devel freetype freetype-devel lsof pcre pcre-devel vixie-cron crontabs icu libicu-devel c-ares libffi-devel bzip2-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel firewalld ipset libpq-devel"
    yum install -y ${yumPacks}

    for yumPack in ${yumPacks}; do
        rpmPack=$(rpm -q ${yumPack})
        packCheck=$(echo ${rpmPack} | grep not)
        if [ "${packCheck}" ]; then
            yum install ${yumPack} -y
        fi
    done
    if [ -f "/usr/bin/dnf" ]; then
        dnf install -y redhat-rpm-config
    fi

    ALI_OS=$(cat /etc/redhat-release | grep "Alibaba Cloud Linux release 3")
    if [ -z "${ALI_OS}" ]; then
        yum install epel-release -y
    fi
}

Install_Deb_Pack() {

    debPacks="wget curl libcurl4-openssl-dev gcc make zip unzip tar openssl libssl-dev gcc libxml2 libxml2-dev zlib1g zlib1g-dev libjpeg-dev libpng-dev lsof libpcre3 libpcre3-dev cron net-tools swig build-essential libffi-dev libbz2-dev libncurses-dev libsqlite3-dev libreadline-dev tk-dev libgdbm-dev libdb-dev libdb++-dev libpcap-dev xz-utils git ufw ipset sqlite3 uuid-dev libpq-dev liblzma-dev"

    DEBIAN_FRONTEND=noninteractive apt-get install -y $debPacks --force-yes

    for debPack in ${debPacks}; do
        packCheck=$(dpkg -l ${debPack})
        if [ "$?" -ne "0" ]; then
            DEBIAN_FRONTEND=noninteractive apt-get install -y $debPack --force-yes
        fi
    done

}

install_pack(){
	if [ -f /usr/bin/yum ];then
		Install_RPM_Pack
	else
		Install_Deb_Pack
	fi
}

install_python(){
	#curl -Ss --connect-timeout 3 -m 60 $download_Url/install/pip_select.sh|bash
	pyenv_path="/www/server/panel"

	if [ -f "$pyenv_path/pyenv/bin/python3.12" ]; then
		mv $pyenv_path/pyenv $pyenv_path/pyenv_python3.12
	fi

	if [ -f "$pyenv_path/pyenv_update-panel/bin/python3.7" ]; then
		if [ -d "$pyenv_path/pyenv" ] && [ ! -f "$pyenv_path/pyenv/bin/python3.7" ]; then
			if [ -d "$pyenv_path/pyenv_restore-panel" ]; then
				rm -rf $pyenv_path/pyenv_restore-panel
			fi
			mv $pyenv_path/pyenv $pyenv_path/pyenv_restore-panel
		fi

		if [ ! -f "$pyenv_path/pyenv/bin/python3.7" ]; then
			mv $pyenv_path/pyenv_update-panel $pyenv_path/pyenv
		fi
	fi

	python_bin=$pyenv_path/pyenv/bin/python
	if [ -f $pyenv_path/pyenv/bin/python ];then
		is_ssl=$($python_bin -c "import ssl" 2>&1 | grep cannot)
		$pyenv_path/pyenv/bin/python3.7 -V
		if [ $? -eq 0 ] && [ -z "${is_ssl}" ]; then
			chmod -R 700 $pyenv_path/pyenv/bin
			is_package=$($python_bin -m psutil 2>&1|grep package)
			if [ "$is_package" = "" ];then
				wget --no-check-certificate -O $pyenv_path/pyenv/pip.txt $download_Url/install/pyenv/pip_en.txt -t 5 -T 15
				$pyenv_path/pyenv/bin/pip install -U pip
				$pyenv_path/pyenv/bin/pip install -U setuptools
				$pyenv_path/pyenv/bin/pip install -r $pyenv_path/pyenv/pip.txt
				$pyenv_path/pyenv/bin/pip install cachelib
			fi
			$pyenv_path/pyenv/bin/pip install cachelib
			source $pyenv_path/pyenv/bin/activate
			chmod -R 700 $pyenv_path/pyenv/bin
			return
		else
			rm -rf $pyenv_path/pyenv
		fi
	fi
	install_pack
	py_version="3.7.8"
	mkdir -p $pyenv_path
	echo "True" >/www/disk.pl
	if [ ! -w /www/disk.pl ]; then
		Red_Error "ERROR: Install python env fielded." "ERROR: path [www] cannot be written, please check the directory/user/disk permissions!"
	fi
	os_type='el'
	os_version='7'
	is_export_openssl=0
	Get_Versions
	echo "OS: $os_type - $os_version"
	is_aarch64=$(uname -a|grep aarch64)
	if [ "$is_aarch64" != "" ];then
		is64bit="aarch64"
	fi
	up_plugin=1

	if [ -f "/www/server/panel/pymake.pl" ];then
		os_version=""
		rm -f /www/server/panel/pymake.pl
	fi

	if [ "${os_version}" != "" ];then
		pyenv_file="/www/pyenv.tar.gz"
		wget --no-check-certificate -O $pyenv_file $download_Url/install/pyenv/pyenv-${os_type}${os_version}-x${is64bit}.tar.gz -t 5 -T 15
		if [ "$?" != "0" ];then
			wget --no-check-certificate -O $pyenv_file $download_Url/install/pyenv/pyenv-${os_type}${os_version}-x${is64bit}.tar.gz -t 5 -T 15
		fi
		tmp_size=$(du -b $pyenv_file|awk '{print $1}')
		if [ $tmp_size -lt 703460 ];then
			rm -f $pyenv_file
			echo "ERROR: Download python env fielded."
		else
			echo "Install python env..."
			tar zxvf $pyenv_file -C $pyenv_path/ >/dev/null
			chmod -R 700 $pyenv_path/pyenv/bin
			if [ ! -f $pyenv_path/pyenv/bin/python ];then
				rm -f $pyenv_file
				Red_Error "ERROR: Install python env fielded."
			fi
			# is_err=$($pyenv_path/pyenv/bin/python3.7 -V 2>&1|grep 'Could not find platform')
			$pyenv_path/pyenv/bin/python3.7 -V
			if [ $? -eq 0 ]; then
				rm -f $pyenv_file
				ln -sf $pyenv_path/pyenv/bin/pip3.7 /usr/bin/btpip
				ln -sf $pyenv_path/pyenv/bin/python3.7 /usr/bin/btpython
				source $pyenv_path/pyenv/bin/activate
				return
			else
				rm -f $pyenv_file
				rm -rf $pyenv_path/pyenv
			fi

		fi
	fi

	cd /www
	python_src='/www/python_src.tar.xz'
	python_src_path="/www/Python-${py_version}"
	wget --no-check-certificate -O $python_src $download_Url/src/Python-${py_version}.tar.xz -t 5 -T 15
	tmp_size=$(du -b $python_src | awk '{print $1}')
	if [ $tmp_size -lt 10703460 ]; then
		rm -f $python_src
		Red_Error "ERROR: Download python source code fielded. Please try to reinstall"
	fi
	tar xvf $python_src
	rm -f $python_src
	cd $python_src_path
	./configure --prefix=$pyenv_path/pyenv
	make -j$cpu_cpunt
	make install
	if [ ! -f $pyenv_path/pyenv/bin/python3.7 ]; then
		rm -rf $python_src_path
		Red_Error "ERROR: Make python env fielded. Please try to reinstall"
	fi
	cd ~
	rm -rf $python_src_path
	wget --no-check-certificate -O $pyenv_path/pyenv/bin/activate $download_Url/install/pyenv/activate.panel -t 5 -T 15
	wget --no-check-certificate -O $pyenv_path/pyenv/pip.txt $download_Url/install/pyenv/pip-3.7.8.txt -t 5 -T 15
	ln -sf $pyenv_path/pyenv/bin/pip3.7 $pyenv_path/pyenv/bin/pip
	ln -sf $pyenv_path/pyenv/bin/python3.7 $pyenv_path/pyenv/bin/python
	ln -sf $pyenv_path/pyenv/bin/pip3.7 /usr/bin/btpip
	ln -sf $pyenv_path/pyenv/bin/python3.7 /usr/bin/btpython
	chmod -R 700 $pyenv_path/pyenv/bin
	$pyenv_path/pyenv/bin/pip install -U pip
	$pyenv_path/pyenv/bin/pip install -U setuptools
	$pyenv_path/pyenv/bin/pip install -U wheel==0.34.2
	$pyenv_path/pyenv/bin/pip install -r $pyenv_path/pyenv/pip.txt

	source $pyenv_path/pyenv/bin/activate
    btpip install psutil
    btpip install gevent
	is_gevent=$($python_bin -m gevent 2>&1 | grep -oE package)
	is_psutil=$($python_bin -m psutil 2>&1 | grep -oE package)
	if [ "${is_gevent}" != "${is_psutil}" ]; then
		Red_Error "ERROR: psutil/gevent install failed!"
	fi
}

sync_python_lib(){
    pip_list=$(pip list 2>/dev/null|grep -v Package|grep -v '\-\-\-\-\-\-'|awk '{print $1}'|xargs)
    $pyenv_path/pyenv/bin/pip install -U pip setuptools
    $pyenv_path/pyenv/bin/pip install $pip_list
}

Get_Versions(){
	redhat_version_file="/etc/redhat-release"
	deb_version_file="/etc/issue"

	if [[ $(grep Anolis /etc/os-release) ]] && [[ $(grep VERSION /etc/os-release|grep 8.8) ]];then
		if [ -f "/usr/bin/yum" ];then
			os_type="anolis"
			os_version="8"
			return
		fi
	fi


	if [ -f "/etc/os-release" ];then
		. /etc/os-release
		OS_V=${VERSION_ID%%.*}
		if [ "${ID}" == "opencloudos" ] && [[ "${OS_V}" =~ ^(9)$ ]];then
			os_type="opencloudos"
			os_version="9"
			return
		fi
	fi
    
	if [ -f $redhat_version_file ];then
		os_type='el'
		is_aliyunos=$(cat $redhat_version_file|grep Aliyun)
		if [ "$is_aliyunos" != "" ];then
			return
		fi

		if [[ $(grep "Alibaba Cloud" /etc/redhat-release) ]] && [[ $(grep al8 /etc/os-release) ]];then
			os_type="ali-linux-"
			os_version="al8"
			return
		fi

		if [[ $(grep "TencentOS Server" /etc/redhat-release|grep 3.1) ]];then
			os_type="TencentOS-"
			os_version="3.1"
			return
		fi

		os_version=$(cat $redhat_version_file|grep CentOS|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '^[0-9]')
		if [ "${os_version}" = "5" ];then
			os_version=""
		fi
		if [ -z "${os_version}" ];then
			os_version=$(cat /etc/redhat-release |grep Stream|grep -oE 8)
		fi
	else
		os_type='ubuntu'
		os_version=$(cat $deb_version_file|grep Ubuntu|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '^[0-9]+')
		if [ "${os_version}" = "" ];then
			os_type='debian'
			os_version=$(cat $deb_version_file|grep Debian|grep -Eo '([0-9]+\.)+[0-9]+'|grep -Eo '[0-9]+')
			if [ "${os_version}" = "" ];then
				os_version=$(cat $deb_version_file|grep Debian|grep -Eo '[0-9]+')
			fi
			if [ "${os_version}" = "8" ];then
				os_version=""
			fi
			if [ "${is64bit}" = '32' ];then
				os_version=""
			fi
		else
			if [ "$os_version" = "14" ];then
				os_version=""
			fi
			if [ "$os_version" = "12" ];then
				os_version=""
			fi
			if [ "$os_version" = "19" ];then
				os_version=""
			fi
			if [ "$os_version" = "21" ];then
				os_version=""
			fi
			if [ "$os_version" = "20" ];then
				os_version2004=$(cat /etc/issue|grep 20.04)
				if [ -z "${os_version2004}" ];then
					os_version=""
				fi
			fi
		fi
	fi
}

update_panel(){

	mypip="/www/server/panel/pyenv/bin/pip"

	pip_list=$($mypip list)
	setuptools_v=$(echo "$pip_list"|grep setuptools)
	if [ "$setuptools_v" = "" ];then
		$mypip install setuptools
	fi
	requests_v=$(echo "$pip_list"|grep requests)
	if [ "$requests_v" = "" ];then
		$mypip install requests
	fi
	openssl_v=$(echo "$pip_list"|grep pyOpenSSL)
	if [ "$openssl_v" = "" ];then
		$mypip install pyOpenSSL
	fi

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

	GEVENT_V=$(echo "$pip_list"|grep "gevent "|awk '{print $2}'|cut -f 1 -d '.')
	if [ "${GEVENT_V}" -le "1" ];then
		$mypip install -I gevent
	fi

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

	psutil=$(echo "$pip_list"|grep psutil)
	if [ "$psutil" = "" ];then
		$mypip install -I psutil
	fi

	telegram_v=$(echo "$pip_list"|grep python-telegram-bot)
	if [ "$telegram_v" = "" ];then
		$mypip install python-telegram-bot==20.3
	fi

	if [ -f "/www/server/panel/plugin/aws_s3/aws_s3_main.py" ]; then
		boto3_v=$(echo "$pip_list"|grep boto3)
		if [ "$boto3_v" = "" ];then
			$mypip install boto3
		fi
	fi

	if [ -f "/www/server/panel/plugin/frp/frp_main.py" ]; then
		toml_v=$(echo "$pip_list"|grep toml)
		if [ "$toml_v" = "" ];then
			$mypip install toml
		fi
	fi

	if [ -f "/www/server/panel/plugin/supervisor/supervisor_main.py" ]; then
		# pyasynchat_v=$(echo "$pip_list"|grep pyasynchat)
		# if [ "$pyasynchat_v" = "" ];then
		# 	$mypip install pyasynchat
		# fi
		supervisor_v=$(echo "$pip_list"|grep supervisor)
		if [ "$supervisor_v" = "" ];then
			$mypip install supervisor==4.2.4 -I
		fi
		Supervisor_plugin=/www/server/panel/plugin/supervisor
		Supervisor_py=/www/server/panel/pyenv/lib/python3.7/site-packages/supervisor

		if [ -d "$Supervisor_py" ]; then
			\cp -rpaf $Supervisor_py/options.py $Supervisor_plugin/options.py.bak
			\cp -rpaf $Supervisor_plugin/options.py $Supervisor_py/options.py

			\cp -rpaf $Supervisor_py/rpcinterface.py $Supervisor_plugin/rpcinterface.py.bak
			\cp -rpaf  $Supervisor_plugin/rpcinterface.py $Supervisor_py/rpcinterface.py
			echo bt > $Supervisor_py/bt.pl
		fi
	fi

    wget --no-check-certificate -t 5 -T 20 -O /tmp/panel.zip $download_Url/install/update/LinuxPanel_EN-${version}.zip
    dsize=$(du -b /tmp/panel.zip|awk '{print $1}')
    if [ $dsize -lt 10240 ];then
        echo "Failed to obtain the update package, please update later or contact: forum.aapanel.com"
        exit;
    fi
    unzip -o /tmp/panel.zip -d $setup_path/server/ > /dev/null
    rm -f /tmp/panel.zip
    cd $setup_path/server/panel/
    check_bt=`cat /etc/init.d/bt|grep BT-Task`
    if [ "${check_bt}" = "" ];then
        rm -f /etc/init.d/bt
        wget --no-check-certificate -O /etc/init.d/bt ${download_Url}/install/src/bt6_en.init -t 5 -T 20
        chmod +x /etc/init.d/bt
    fi
    rm -f /www/server/panel/*.pyc
    rm -f /www/server/panel/class/*.pyc
    # if [ ! -f $setup_path/server/panel/config/config.json ];then
    #     wget -T 5 -O $setup_path/server/panel/config/config.json $download_Url/install/pyenv/config/config.json
    #     wget -T 5 -O $setup_path/server/panel/config/dns_api.json $download_Url/install/pyenv/config/dns_api.json
    # fi

    chattr -i /etc/init.d/bt
    chmod +x /etc/init.d/bt
    #if [ $up_plugin = 1 ];then
    #    $pyenv_bin/python /www/server/panel/tools.py update_to6
    #fi

}

update_start(){
    echo "====================================="
    echo "Start upgrading aaPanel old version, please wait..."
    echo "====================================="
}


update_end(){
    # $pyenv_bin/pip install dnspython enum34 IPy pycurl docker pyinotify
    echo "====================================="
    rm -f /dev/shm/bt_sql_tips.pl
    kill $(ps aux|grep -E "task.py|main.py"|grep -v grep|awk '{print $2}') &>/dev/null
    bash /www/server/panel/init.sh restart
    # echo 'True' > /www/server/panel/data/restart.pl
    # pkill -9 gunicorn &>/dev/null &
    echo "Successfully upgraded to [$version]${Ver}";
}


update_start
check_panel
select_node
install_python
get_version
update_panel
update_end
