#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
LANG=en_US.UTF-8
remote_dir="coll"
install_version=$2

install_pack(){
	#安装依赖
	if [ -f /usr/bin/yum ];then
		yum install gcc lsof unzip libffi-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel wget git libevent make cmake -y
	else
		apt install gcc lsof net-tools swig build-essential unzip libffi-dev zlib1g.dev libbz2-dev libssl-dev libncurses-dev libsqlite3-dev libreadline-dev tk-dev libgdbm-dev libdb-dev libdb++-dev libpcap-dev xz-utils wget git make cmake -y
	fi
}

install_pyenv(){
	#安装pyenv
	pyenv_bin=/root/.pyenv/bin/pyenv
	if [ ! -f $pyenv_bin ];then
		git clone https://github.com/pyenv/pyenv.git /root/.pyenv
	fi

	if [ ! -f $pyenv_bin ];then
		echo "==========================================================="
		echo "无法安装pyenv,请使用以下命令尝试手动安装:"
		echo "git clone https://github.com/pyenv/pyenv.git /root/.pyenv"
		echo "==========================================================="
		exit 0
	fi
}


install_memcached(){
	#安装memcached
	memcached_bin1=/etc/init.d/memcached
	memcached_bin2=/usr/bin/memcached
	memcached_port=11211
	if [ ! -f $memcached_bin1 ] &&  [ ! -f $memcached_bin2 ];then
		is_listen=$(netstat -ln|grep $memcached_port|grep LISTEN)
		if [ "$is_listen" != "" ];then
			return
		fi
		
		if [ -f /usr/bin/yum ];then
			yum install memcached memcached-devel -y
			if [ -f /etc/sysconfig/memcached ];then
				systemctl enable memcached
				systemctl start memcached
			else
				/etc/init.d/memcached start
				chkconfig --level 2345 memcached on
			fi
		else
			apt install memcached -y
			apt install libmemcached-dev -y
			update-rc.d memcached defaults
		fi
		
		if [ -f $memcached_bin1 ];then
			sed -i "s/OPTIONS=\"\"/OPTIONS=\"-l 127.0.0.1\"/" $memcached_bin1
		else
			sed -i "s/OPTIONS=\"\"/OPTIONS=\"-l 127.0.0.1\"/" /etc/sysconfig/memcached
		fi
		
		if [ -f /etc/init.d/memcached];then
			/etc/init.d/memcached restart
		else
			systemctl restart memcached
		fi
	fi

	is_start=$(ps -ef | grep -v grep | grep memcached)
	if [ "$is_start" ];then
		echo "memcached 已正常启动。"
	else
		echo "memcached 未能正常启动，可能会导致云控无法正常使用，请在论坛或客服需求技术支持。"
	fi
}

env_path=/www/server/coll/pyenv

install_python(){
	#安装指定Py版本
	cd /root
	python_version=3.7.4
	is_err=$(cat $env_path/bin/pip|grep "pyenv$python_version")
	if [ "$is_err" != "" ];then
		rm -rf $env_path
	fi
	if [ ! -f $env_path/bin/python ];then
		src_file=/root/Python-$python_version.tar.xz
		src_path=/root/Python-$python_version
		rm -rf $src_path
		mkdir -p $env_path
		wget -O $src_file http://download.bt.cn/src/Python-$python_version.tar.xz -T 5
		tar xvf $src_file
		cd $src_path
		./configure --prefix=$env_path
		cpu_cpunt=$(cat /proc/cpuinfo|grep processor|wc -l)
		make -j$cpu_cpunt
		make install
		
		if [ ! -f $env_path/bin/python3.7 ];then
			echo "==========================================================="
			echo "无法安装Python虚拟环境,请使用以下命令尝试手动安装:"
			echo "$pyenv_bin install $python_version -v"
			echo "==========================================================="
			exit 0
		fi
		
		if [ ! -f $env_path/bin/python ];then
			ln -sf $env_path/bin/python3.7 $env_path/bin/python
		fi
		
		\cp -arf $env_path/bin/pip3.7 $env_path/bin/pip
		chmod +x $env_path/bin/pip
		rm -rf $src_path $src_file
		cd $env_path
	fi
}

init_pyenv(){
	#初始化pyenv环境变量
	if [ ! -f $env_path/bin/activate ];then
		wget -O $env_path/bin/activate http://download.bt.cn/install/pyenv/activate
	fi
	source $env_path/bin/activate
}

install_pypack(){
	#安装PYthon依赖包
	cd $env_path
	curl -Ss --connect-timeout 3 -m 60 http://download.bt.cn/install/pip_select.sh|bash
	wget -O /www/server/coll/requirement.txt http://download.bt.cn/install/${remote_dir}/requirement-coll.txt
	$env_path/bin/pip3.7 install pip -U
	$env_path/bin/pip3.7 install -r /www/server/coll/requirement.txt
	is_install=$($env_path/bin/python -m M2Crypto 2>&1|grep 'package and cannot be directly executed')
	if [ "$is_install" = "" ];then
		echo "==========================================================="
		echo "安装Python依赖包失败!"
		echo "==========================================================="
		exit 0 
	fi
	$env_path/bin/pip install pycryptodome -I
}

install_side(){
	#安装被控端
	if [ -n "$install_version" ]; then
        echo "开始安装云控v${install_version}"
	    wget -O /tmp/coll.zip http://download.bt.cn/install/${remote_dir}/update/Coll-${install_version}.zip -T 5
    else
        echo "No version set."
	    wget -O /tmp/coll.zip http://download.bt.cn/install/${remote_dir}/coll.zip -T 5
    fi
	
	unzip -o /tmp/coll.zip -d /www/server/coll/ &> /dev/null
	side_path=/www/server/coll
	if [ ! -f $side_path/init.sh ];then
		echo "==========================================================="
		echo "文件下载失败!"
		echo "==========================================================="
		exit 0 
	fi

	if [ ! -d $side_path/logs ]; then
		mkdir $side_path/logs
		touch $side_path/logs/error.log
	fi

	if [ ! -d $side_path/data ]; then
		mkdir -p $side_path/data
	fi

	if [ ! -d $side_path/config ]; then
		mkdir -p $side_path/config
	fi

	wget -O /www/server/coll/data/node.json http://download.bt.cn/install/${remote_dir}/default_data/node.json
	wget -O /www/server/coll/config/config.json http://download.bt.cn/install/${remote_dir}/default_config/config.json

	if [ ! -f /www/server/coll/config/menu.json ];then
		wget -O /www/server/coll/config/menu.json http://download.bt.cn/install/${remote_dir}/default_config/menu.json
	fi
	if [ ! -f /www/server/coll/data/data.db ];then
		wget -O /www/server/coll/data/data.db http://download.bt.cn/install/${remote_dir}/default_data/data.db
	fi
	if [ ! -f /www/server/coll/data/port.pl ];then
		wget -O /www/server/coll/data/port.pl http://download.bt.cn/install/${remote_dir}/default_data/port.pl
	fi

	if [ ! -f /www/server/coll/data/timeout.pl ];then
		echo 15 > /www/server/coll/data/timeout.pl
	fi
	#  生成安全入口文件
	admin_auth="/www/server/coll/data/admin_path.pl"
	if [ ! -f ${admin_auth} ];then
		auth_path=$(cat /dev/urandom | head -n 16 | md5sum | head -c 8)
		echo "/${auth_path}" > ${admin_auth}
	fi
	auth_path=$(cat ${admin_auth})

	chmod +x $side_path/baota_coll
	\cp -arf $side_path/init.sh /etc/init.d/baota
	chmod +x /etc/init.d/baota
	ln -sf /etc/init.d/baota /usr/bin/baota
	/etc/init.d/baota start
	/etc/init.d/baota reload
	rm -f /tmp/coll.zip
	sleep 1
}

set_firewall_or_services(){
	#设置服务和防火墙
	if [ ! -f $side_path/data/port.pl ]; then
		echo 801 > $side_path/data/port.pl
	fi
	port=$(cat $side_path/data/port.pl)
	if echo $port | grep -q '[^0-9]'
	then
    	port=801
		echo 801 > $side_path/data/port.pl
	fi
	if [ -n $port ]; then
    	port=801
		echo 801 > $side_path/data/port.pl
	fi	
	if [ -f /usr/bin/yum ];then
		chkconfig --add baota
		chkconfig --level 2345 baota on
		if [ -f /etc/init.d/iptables ];then
			iptables -I INPUT -p tcp -m state --state NEW -m tcp --dport $port -j ACCEPT
			service iptables save
		fi

		if [ -f /usr/bin/firewall-cmd ];then
			firewall-cmd --permanent --zone=public --add-port=$port/tcp
			firewall-cmd --reload
		fi
	else
		update-rc.d baota defaults
		if [ -f "/usr/sbin/ufw" ];then
			ufw allow $port/tcp
			ufw reload
		fi
	fi
}

install_pack
install_python
init_pyenv
install_pypack
install_memcached
install_side

set_firewall_or_services

version_gt() { 
	test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"; 
}


coll_version=`cat /www/server/coll/version.pl`
if version_gt "2.5.5" $coll_version; then
	if [ ! -f /www/server/coll/data/tips.pl ];then
		echo ssl > /www/server/coll/data/tips.pl
	fi
else
	echo update > /www/server/coll/data/tips.pl
fi

if [ -f /www/server/coll/coll_patch.py ]; then
	echo "正在执行升级补丁程序..."
	/www/server/coll/pyenv/bin/python /www/server/coll/coll_patch.py
	echo "补丁程序执行完毕。"
fi

address=`curl -sS --connect-timeout 10 -m 60 https://www.bt.cn/Api/getIpAddress`

echo "==========================================================="
echo "安装成功!"
echo "==========================================================="
if [ ! -f /www/server/coll/data/ssl.pl ];then
	echo "http://$address:$port$auth_path"
else
	echo "https://$address:$port$auth_path"
fi
$env_path/bin/python $side_path/pass.py auto
echo "==========================================================="