#!/bin/bash
echo "============================================================="
echo "                   ViewWatch Auto Setup                      "
echo "                   Version: 1.0                              "
echo "============================================================="

curdir=$(cd "$(dirname "$0")";pwd)

# 初始化配置
config_file="server_global.config"
if [ ! -f $config_file ];then
	echo "ERROR:${config_file}配置文件不存在，请先检查配置，再执行安装。。。"
	exit
fi

# 获取配置文件：数据库及密码
a=`grep 'db_username' $config_file`
db_username=`echo ${a#*=}`
# 据库配密码
a=`grep 'db_password' $config_file`
db_password=`echo ${a#*=}`


# 安装yum 软件源
install_reposity() {
	rpm -qa|grep -i gcc-c++ > /dev/null 2>&1 && rpm -qa|grep -i make > /dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo "配置yum reposity"
		cp -rf reposity/* /etc/yum.repos.d/
		yum -y install gcc gcc-c++ && yum -y install make
		if [ $? -ne 0 ] ; then
			install_reposity
		else
			install_all_server
		fi
	else 
		echo "配置yum reposity ok"
		install_all_server
	fi
}

# 安装java jdk
install_jdk() {
	if type -p /usr/java/jdk1.8.0_311/bin/java &>/dev/null; then
		echo "========== Java is installed！=========="
		return 1
	fi
	echo "===================Jdk安装==================="
	#解压安装
	mkdir -p /usr/java
	cd jdk8
	tar -zxvf jdk-8u311-linux-x64.tar.gz -C /usr/java
	#配置环境变量
	cat /etc/profile | grep JAVA_HOME=/usr/java/jdk1.8.0_311
	if [ $? -ne 0 ] ; then
		echo "export JAVA_HOME=/usr/java/jdk1.8.0_311" >> /etc/profile
		echo "export PATH=\$JAVA_HOME/bin:\$PATH" >> /etc/profile
		echo "export CLASSPATH=.:\$JAVA_HOME/lib/dt.jar:\$JAVA_HOME/lib/tools.jar" >> /etc/profile

		source /etc/profile
		echo "setting path successful."
	fi
	java -version
	echo "========== install jdk success!!!========== "
	cd ..
}

#开放常用端口
firewall_add_port(){
    #firewall-cmd --zone=public --add-port=80/tcp --permanent
    firewall-cmd --zone=public --add-port=3306/tcp --permanent
    firewall-cmd --zone=public --add-port=9901/tcp --permanent
    firewall-cmd --zone=public --add-port=6000/tcp --permanent
    firewall-cmd --zone=public --add-port=9999/tcp --permanent
    firewall-cmd --zone=public --add-port=9000/tcp --permanent
    firewall-cmd --zone=public --add-port=10430/tcp --permanent
    firewall-cmd --zone=public --add-port=10432/tcp --permanent
    firewall-cmd --reload
    firewall-cmd --list-ports
}

install_tomcat()
{
	echo "===================Tomcat安装==================="
	echo "start install tomcat..."
	#killall -9 java
	rm -rf /usr/local/apache-tomcat-*
	rm -rf /usr/local/tomcat
	cd tomcat9
	tar zxvf apache-tomcat-9.0.0.M8.tar.gz -C /usr/local/
	ln -s /usr/local/apache-tomcat-9.0.0.M8 /usr/local/tomcat
	cp tomcat  /etc/init.d/
	chmod 777 /etc/init.d/tomcat
	#开放8080端口
	firewall-cmd --zone=public --add-port=8080/tcp --permanent
	firewall-cmd --reload
	service tomcat start
	#cd /usr/local/tomcat/bin
	#./startup.sh
	chkconfig --add tomcat
	chkconfig tomcat on
	cd ..
	echo "===================Tomcat安装完成==================="
}


install_mysql(){
	# 安装依赖
	#apt install numactl
	#apt install libaio-dev
	#check if libaio installed	
	if type -p mysql &>/dev/null; then
		echo "MySQL 已经安装！如需要安装，请先卸载MySQL..."
		return 1
	fi
	echo "===================mysql安装==================="
	#与后面endtime结合现实脚本安装时间
	start_time=$(date +%s)

	#yum -y install gcc gcc-c++ openssl openssl-devel libaio libaio-devel  ncurses  ncurses-devel  >> /dev/null
	rpm -qa|grep -i libaio > /dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo "libaio package missing, mysql install will exit! "
		echo "Try \"yum install -y libaio\""
		yum -y install libaio
		yum -y install libaio-devel 
		#exit
	fi
	rpm -qa|grep -i openssl> /dev/null 2>&1
	if [ $? -ne 0 ] ; then
		echo "openssl package missing, mysql install will exit! "
		echo "Try \"yum install -y openssl\""
		yum -y install openssl
		yum -y install openssl-devel 
		#exit
	fi

	#解决缺少libtinfo.so.5的问题
	if [ -L /usr/lib64/libtinfo.so.5 ] 
	then 
		echo "/usr/lib64/libtinfo.so.5 is exist"
	else
		sudo ln -s /usr/lib64/libtinfo.so.6.1 /usr/lib64/libtinfo.so.5
	fi

	#解压
	cd mysql
	tar -Jxvf mysql-8.0.27-linux-glibc2.12-x86_64.tar.xz
	#移动到/usr/local/mysql
	mv mysql-8.0.27-linux-glibc2.12-x86_64 /usr/local/mysql

	# 创建数据库文件目录和创建日志目录
	mkdir /usr/local/mysql/{data,log}
	#添加用户组
	groupadd mysql
	useradd -r -g mysql -s /bin/false mysql
	#cd /usr/local/mysql

	chown -R mysql:mysql /usr/local/mysql
	chmod 750 /usr/local/mysql/{data,log}
	
	#配置/etc/my.cnf
	#cat > /etc/my.cnf
	#清空文件
	cat /dev/null  > /etc/my.cnf
	echo "[mysqld]" >> /etc/my.cnf
	echo "port=3306" >> /etc/my.cnf
	echo "datadir=/usr/local/mysql/data" >> /etc/my.cnf
	echo "log-error=/usr/local/mysql/log/mysql-err.log" >> /etc/my.cnf
	echo "user=mysql" >> /etc/my.cnf
	echo "socket=/tmp/mysql.sock" >> /etc/my.cnf
	#mysql5.7以上版本，关闭ONLY_FULL_GROUP_BY模式
  	echo "sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION" >> /etc/my.cnf

   
	#配置环境变量
	echo "export PATH=$PATH:/usr/local/mysql/bin"  >>  /etc/profile
	source /etc/profile

	#初始化数据库
	/usr/local/mysql/bin/mysqld  --initialize  --user=mysql  --basedir=/usr/local/mysql　--datadir=/usr/local/mysql/data   >>  /dev/null
	#制作启动文件
	cp  /usr/local/mysql/support-files/mysql.server  /etc/init.d/mysqld
	sed  -i  's/^basedir=/basedir=\/usr\/local\/mysql/'  /etc/init.d/mysqld
	sed  -i  's/^datadir=/datadir=\/usr\/local\/mysql\/data/'  /etc/init.d/mysqld
	chmod  755 /etc/init.d/mysqld

	#启动mysql服务
	/etc/init.d/mysqld start
	#关闭mysql服务　
	#/etc/init.d/mysqld stop
	echo "===================mysql安装完成==================="

	#修改mysql登录密码
	b=`grep  'temporary password'   /usr/local/mysql/log/mysql-err.log`
	a=`echo ${b##*localhost:}`
	echo $a

	#创建/usr/local/mysql/bin/mysql软连接，便于命令行直接执行mysql
	ln  -s  /usr/local/mysql/bin/mysql   /usr/bin/mysql
	# 设置root的新密码
	root_passwd="bsy#%1q2R3tz"
	#mysql -e　可以直接在命令行执行命令,123456是设定的新密码
	mysql -uroot -p"${a}" -e  "ALTER USER 'root'@'localhost'  IDENTIFIED  BY '${root_passwd}'"  --connect-expired-password
	echo  "===================mysql密码修改成功==================="


	#创建用户并授权,mysql8不允许root用户授权给自己
	mysql -u root -p"${root_passwd}" -e "create user '${db_username}'@'%' identified by '${db_password}'"
	mysql -u root -p"${root_passwd}" -e "GRANT ALL PRIVILEGES ON *.* TO '${db_username}'@'%'"
	mysql -u root -p"${root_passwd}" -e "FLUSH PRIVILEGES;"
	echo  "===================mysql连接权限修改成功==================="
	echo "import videowatch databases..."
	mysql -u "${db_username}" -p"${db_password}" < init_viewwatch.sql

	echo "update tale server ip..."
	mysql -u "${db_username}" -p"${db_password}" -e "update viewwatch.server set wan_ip='${wan_ip}',lan_ip='${wan_ip}' where id='ccs_001' or id='cdn001'"

	#开放3306端口
	firewall-cmd --zone=public --add-port=3306/tcp --permanent
	firewall-cmd --reload
	end_time=$(date +%s)
	cost_time=$((end_time - start_time))
	echo "===================返回到安装目录==================="
  	cd ..
}

#安装编译环境
install_Compile(){
	# 安装gcc gcc-c++
	rpm -qa|grep -i gcc-c++ > /dev/null 2>&1
	if [ $? -ne 0 ] ; then
		yum install -y gcc gcc-c++
	fi
	rpm -qa|grep -i make > /dev/null 2>&1
	# 安装 make
	if [ $? -ne 0 ] ; then
		yum install -y make
	fi
	
	#ubantu 
	#apt-get install gcc gcc-c++
}

#安装依赖包
install_package(){
	#centos 安装依赖包
	yum install -y pcre pcre-devel 
	yum install -y openssl openssl-devel 
	yum install -y zlib zlib-devel gd gd-devel

	#ubantu 安装依赖包
	#apt-get install pcre pcre-devel 
	#apt-get install openssl openssl-devel 
	#apt-get zlib zlib-devel gd gd-devel
	
}

install_nginx()
{
	#判断nginx是否已经安装
	if type -p nginx &>/dev/null; then
		echo "nginx 已经安装！如需要安装，请先卸载 nginx..."
		if  [ -d "./dist" ];then
			cp -R ./dist /usr/local/nginx/html/dist
		fi
		return 1
	fi
	echo -e "\033[5;32m=========="安装编译环境"==========\033[0m"
	install_Compile	
	echo -e "\033[5;32m=========="安装依赖包"==========\033[0m"
	install_package
	#echo -e "\033[5;32m=========="下载安装nginx"==========\033[0m"
	#wget -c http://nginx.org/download/nginx-1.20.2.tar.gz
	# 下载完成
	#解压安装
	cd nginx
	tar -zxvf nginx-1.20.2.tar.gz 
	sleep 1
	cd nginx-1.20.2
	./configure --prefix=/usr/local/nginx
	make && make install

	echo "===================修改nginx配置文件==================="
	if [ -f "../nginx.conf" ];then
		echo "备份初始nginx配置文件..."
		mv /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf_bak 
		cp ../nginx.conf /usr/local/nginx/conf/nginx.conf
	fi
	echo "===================部署监视器后台web页面==================="
	if  [ -d "../../dist" ];then
		cp -R ../../dist /usr/local/nginx/html/dist
	fi
	#添加环境变量，建立软连接
	ln -s /usr/local/nginx/sbin/nginx /usr/local/bin/
	#启动nginx
	nginx -t
	nginx
	nginx -v
	#开启参数
	#firewall_add_port 80
	netstat -ntlp | grep nginx
	if [ $? -eq 0 ];then
		echo "开启nginx服务成功"
	else
		echo "开启nginx服务失败"
	fi
	echo "===================返回到安装目录==================="
  	cd ../../
}
#rpm 安装redis
install_rpm_redis(){
	if rpm -q redis &>/dev/null; then
		echo "redis已经安装！如需要安装，请先卸载 redis..."
		return 1
	fi
	# 按照依赖
	yum install glibc
  	#安装redis
  	echo "===================安装Redis==================="
  	cd redis
	rpm -ivh redis-6.0.9-5.module_el8.4.0+956+a52e9aa4.x86_64.rpm
	#设置后台静默启动
	sed -i 's/daemonize no/daemonize yes/' /etc/redis.conf
	# 重启redis服务
	echo "===================重启Redis==================="
	systemctl restart redis.service
	 # 设置redis服务为开机自启
	systemctl enable redis.service
	echo "返回到安装目录..."
  	cd ..
}
# 安装ffmpeg依赖 yasm
install_yasm(){
	echo -e "\033[5;32m=========="安装编译环境"==========\033[0m"
	install_Compile	
	echo -e "\033[5;32m=========="安装依赖包"==========\033[0m"
	install_package
 	echo "===================安装yasm==================="
 	tar -xvf yasm-1.3.0.tar.gz
 	cd yasm-1.3.0
 	./configure && make && make install
 	cd ..
}
# 安装ffmpeg
install_ffmpeg(){
	if type -p ffmpeg &>/dev/null; then
		echo "redis已经安装！如需要安装，请先卸载 redis..."
		return 1
	fi
  	cd ffmpeg
  	# 安装依赖 yasm
  	install_yasm
  	#安装ffpeg
  	echo "===================安装ffmpeg==================="
  
  	tar -xvf ffmpeg-4.1.6.tar.gz
  	cd ffmpeg-4.1.6/
  	./configure && make && make install
  	ffmpeg -version
  	echo "返回到安装目录..."
  	cd ../../
}

#安装cdn服务
install_stream_cdn(){
	tempFile="/usr/local/cdnd"
	if [ -f "$tempFile" ];then
		echo "cdn已经安装！如需要安装，请先删除cdn..."
		return 1
	fi
	echo "===================安装cdn服务==================="
	cd cdn
	chmod +x install
	./install
	if [ $? -eq 0 ];then
		echo "启动cdn 服务..."
		service cdnd start
	fi
	echo "返回到安装目录..."
	cd ..
}

# 部署java代码服务
install_viewwatch_service(){
	echo $config_file
	# 获取配置文件：安装目录
	a=`grep 'project_workplace' $config_file`
	project_workplace=`echo ${a#*=}`
	echo "目录：$project_workplace"
	# 创建项目文件目录
	if [ ! -d "$project_workplace" ];then
		echo "创建项目目录..."
		mkdir -p $project_workplace
	fi
	echo "项目程序文件复制..."
	cp -Rf boshiyuan-api-viewwatch/ $project_workplace
	cd $project_workplace/boshiyuan-api-viewwatch
	chmod -Rf 777 /upload
	chmod +x serv-start.sh
	#echo "停止程序..."
	#eval "./serv-start.sh stop"
	echo "启动程序..."
	eval "./serv-start.sh start"
}
# 初始化配置,获取配置文件值
init_all_config() {
	# 网卡
	a=`grep 'network_device' $config_file`
	network_device=`echo ${a#*=}`
	# 网卡
	b=`grep 'wan_ip' $config_file`
	wan_ip=`echo ${b#*=}`
	# 据库配置账号
	c=`grep 'db_username' $config_file`
	db_username=`echo ${c#*=}`
	# 据库配密码
	d=`grep 'db_password' $config_file`
	db_password=`echo ${d#*=}`
	# 监视器图片上传目录
	e=`grep 'upload_path' $config_file`
	upload_path=`echo ${e#*=}`
	# 监视器视频文件所在目录
	f=`grep 'media_root' $config_file`
	media_root=`echo ${f#*=}`
	# 配置cdn网卡
	cdn_config="./cdn/config/config.xml"
	if [ -f "$cdn_config" ];then
		sed -i 's/<networkdev>.*<\/networkdev>/<networkdev>'"${network_device}"'<\/networkdev>/g' $cdn_config
	fi
	# 配置web数据api服务ip
	web_config="./dist/static/config.js"
	if [ -f "$web_config" ];then
		sed -i 's/"baseUrl.*/"baseUrl":"http:\/\/'"${wan_ip}"':10432\/"/' $web_config
	fi
	# 修改java配置
	spring_config="./boshiyuan-api-viewwatch/config/application-prod.properties"
	if [ -f "$spring_config" ];then
		sed -i 's/^spring.datasource.username.*/spring.datasource.username='"${db_username}"'/' $spring_config
		sed -i 's/^spring.datasource.password.*/spring.datasource.password='"${db_password}"'/' $spring_config
		sed -i 's/^fileupload.url.*/fileupload.url=http:\/\/'"${wan_ip}"'/' $spring_config
		sed -i 's/^fileupload.uploadPath.*/fileupload.uploadPath='"${upload_path//\//\\\/}"'/' $spring_config
		sed -i 's/^fileupload.mediaRoot.*/fileupload.mediaRoot='"${media_root//\//\\\/}"'/' $spring_config
	fi

}

# 设置服务开机启动
power_start_up() {
    cd $curdir

	# nginx开机启动
	if [ ! -f /etc/systemd/system/nginx.service ];then
		cp -f nginx/nginx.service /etc/systemd/system
		chmod +x /etc/systemd/system/nginx.service
		systemctl enable nginx.service
	fi

	# mysql开机启动
	if [ ! -f /etc/systemd/system/mysql.service ];then
		cp -f mysql/mysql.service /etc/systemd/system
		chmod +x /etc/systemd/system/mysql.service
		# restorecon命令恢复SELinux文件安全
		restorecon -r -v /usr/local/mysql/bin/
		systemctl enable mysql.service
	fi

	# cdn开机启动
	if [ ! -f /etc/systemd/system/cdn.service ];then
		cp -f cdn/cdn.service /etc/systemd/system
		chmod +x /etc/systemd/system/cdn.service
		restorecon -r -v /usr/local/cdn/
		systemctl enable cdn.service
	fi

	# java开机启动
	if [ ! -f /etc/systemd/system/boshiyuan-viewwatch.service ];then
		cp -f boshiyuan-api-viewwatch/boshiyuan-viewwatch.service /etc/systemd/system
		chmod +x /etc/systemd/system/boshiyuan-viewwatch.service
		restorecon -r -v $project_workplace/boshiyuan-api-viewwatch
		semanage fcontext -a -t bin_t "$project_workplace/boshiyuan-api-viewwatch(/.*)?"
		systemctl enable boshiyuan-viewwatch.service
	fi
	# 重启配置
	systemctl daemon-reload


}

# 一键安装所有
install_all_server(){
	install_stream_cdn
	install_jdk
	install_mysql
	install_ffmpeg
	install_nginx
	install_rpm_redis
	install_viewwatch_service
	firewall_add_port
	power_start_up
}

# 安装提示
show_help()
{
	echo "1. Install stream cdn server"
	echo "2. Install java JDK"
	echo "3. Install MySQL"
	echo "4. Install ffmpeg"
	echo "5. Install nginx"
	echo "6. Install Redis"
	echo "7. Add firewall Port"
	echo "8. Install videowatch server"
	echo "9. Install all server"
	echo "10.Server power start up"
	echo "0. Exit"
}

#加载全局配置
init_all_config
# 配置软件镜像源
# install_reposity
while :
do
	show_help
	read -p "choose[0-9]:" num
	if [ $num -eq 1 ] > /dev/null 2>&1; then
		install_stream_cdn
	elif [ $num -eq 2 ] > /dev/null 2>&1; then
		install_jdk
	# elif [ $num -eq 3 ] > /dev/null 2>&1; then
	# 	install_tomcat
	elif [ $num -eq 3 ] > /dev/null 2>&1; then
		install_mysql
	elif [ $num -eq 4 ] > /dev/null 2>&1; then
		install_ffmpeg
	elif [ $num -eq 5 ] > /dev/null 2>&1; then
		install_nginx
	elif [ $num -eq 6 ] > /dev/null 2>&1; then
		install_rpm_redis
	elif [ $num -eq 7 ] > /dev/null 2>&1; then
		firewall_add_port
	elif [ $num -eq 8 ] > /dev/null 2>&1; then
		install_viewwatch_service
	elif [ $num -eq 9 ] > /dev/null 2>&1; then
		install_reposity
	elif [ $num -eq 10 ] > /dev/null 2>&1; then
		power_start_up
	elif [ $num -eq 0 ] > /dev/null 2>&1; then
		echo "bye"
		exit
	else
		echo "Wrong choice, select again!"
	fi
done