#!/usr/bin/env bash
# 文件名: ss5_deploy.sh
# 功  能: 周期性探测系统Socket业务服务端口，失败则重启进程
# 树辉<shuhui@vqiu.cn>



# 安装Nginx
yum -y install nginx
systemctl start nginx
systemctl enable nginx

cat >/usr/local/bin/ss5_monitor<<EOF
#!/usr/bin/env bash
# 文件名: ss5_monitor_
# 功  能: 周期性探测系统Socket业务服务端口，失败则重启进程
# 树辉<shuhui@vqiu.cn>
HOST=127.0.0.1                   # 探测的主机地址
PROTOCOL=tcp                     # 探测的协议
USER=123456                      # 用户名
PASS=654321                      # 密码
PORT=5555                        # 业务端口号
INTERVAL=5                       # 检测间隔时间(单位:秒)
TIMEOUT=1                        # 检测超时时间(单位:秒)
LOGFILE=/var/log/port_proble.log # 日志文件


while true
do
	time=\$(date +%F' '%T)
	#timeout \$TIMEOUT bash -c "</dev/\${PROTOCOL}/\${HOST}/\${PORT} >/dev/null 2>&1"
	curl -I -s /dev/null --connect-timeout \${TIMEOUT} --socks5 \${USER}:\${PASS}@\${HOST}:\${PORT} http://\$HOST >/dev/null 2>&1
	if [[ \$? -eq 0 ]]
	then
		echo "[+] \$time \${HOST}:\${PORT} is up" | tee -a \${LOGFILE}
	else
		echo "[-] \$time \${HOST}:\${PORT} is down" | tee -a \${LOGFILE}

		service ss5 restart
		if [[ \$? -eq 0 ]]
		then
			echo "[+] \$time Service: ss5 restart succeed." | tee -a \${LOGFILE}
		else
			echo "[-] \$time Service: ss5 restart failed." | tee -a \${LOGFILE}
		fi
	fi

	sleep \$INTERVAL
done
EOF

chmod +x /usr/local/bin/ss5_monitor

cat >/usr/lib/systemd/system/ss5-monitor.service<<EOF
[Unit]
Description=Virtual IP Control Service
ConditionPathExists=/usr/local/bin/ss5_monitor

[Service]
Type=simple
ExecStart=/usr/local/bin/ss5_monitor

[Install]
WantedBy=multi-user.target
EOF


systemctl daemon-reload
systemctl restart ss5-monitor.service
systemctl enable ss5-monitor.service
