#!/bin/bash
# 文件名: monit-deploy-wy.sh
# 功能: 部署 monit 脚本
# 作者: 树辉
# 版本: v1.0

ROOT_UID=0                              # root UID
E_NOTROOT=67                            # 非 root 退出代码
CONF=/etc/monitrc                       # monit 主配置文件
        
SSH_PORT=22                             # SSH 监听端口

### SMTP 配置
SMTP_SERV="smtp.exmail.qq.com"	        # SMTP 服务器地址
SMTP_PORT=25					        # SMTP 传送端口
SMTP_USER="monitor@test.com"            # SMTP 用户名
SMTP_PASS="iHFPzmbvvalhre"              # SMTP 认证密码

ALTER_USER="shui@vqiu.cn"               # 报警接收人[建议使用邮件组]

if [[ "$UID" -ne "$ROOT_UID" ]]
then
	echo "Must be root role to run this script!"
	exit $E_NOTROOT
fi

if [[ ! -f /usr/bin/monit ]]
then
	yum -y install monit
	\cp $CONF $CONF.default
fi

cat > $CONF <<EOF
set daemon 60                                   # 监控周期
set logfile /var/log/monit.log                  # monit日志
#set httpd port 2812 and                         # monit内置了一个用于查看被监视服务
#    use address 0.0.0.0/0                       # 监听网卡 IP 地址
#    allow 0.0.0.0/0                             # 允许本地访问
#    allow admin:monit                           #设置使用用户名admin和密码monit

# 设置 SMTP
set mailserver $SMTP_SERV port $SMTP_PORT USERNAME "$SMTP_USER" PASSWORD "$SMTP_PASS" 
set mail-format {
    from: $SMTP_USER
    subject: \$SERVICE \$EVENT at \$DATE
    message: Monit \$ACTION \$SERVICE at \$DATE on \$HOST: \$DESCRIPTION.
}

# 指定邮件接收者
set alert $ALTER_USER with reminder on 3 cycles

# 监控 sshd 服务
check process sshd with pidfile /var/run/sshd.pid
start program "/usr/bin/systemctl start sshd.service"
stop program "/usr/bin/systemctl stop sshd.service"
  if failed port $SSH_PORT protocol ssh then restart
  if 5 restarts within 5 cycles then timeout

# 监控 zabbix 服务
check process nginx with pidfile /tmp/zabbix_agentd.pid
start program = "systemctl start zabbix-agent"
stop program = "systemctl stop zabbix-agent"
  if failed host 127.0.0.1 port 10050 protocol zabbix_agentd then restart

# 监控nginx服务
check process nginx with pidfile /opt/run/nginx.pid
start program = "/usr/bin/systemctl start nginx"
stop program = "/usr/bin/systemctl stop nginx"
  if failed host localhost port 80 protocol http then restart
EOF

# 设置权限
/usr/bin/chmod 0700 $CONF

# 启动 monit 服务
/usr/bin/monit -t
if [[ $? -eq 0 ]]
then
    /usr/bin/systemctl restart monit.service
    /usr/bin/systemctl enable monit.service
fi
