#!/bin/bash

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then
  echo "请使用root权限运行此脚本"
  exit 1
fi

# 安装函数
install_nginx_monitor() {
    # 创建Nginx监控脚本
    cat > /usr/local/bin/nginx_monitor.sh << 'EOL'
#!/bin/bash

# 判断命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 检查Nginx是否运行
is_nginx_running() {
    # 仅匹配实际Nginx进程：例如"nginx: master process"或"nginx: worker process"
    pgrep -f "^nginx: (master|worker) process" >/dev/null 2>&1
}

# 启动Nginx
start_nginx() {
    if command_exists systemctl; then
        systemctl start nginx
    elif command_exists service; then
        service nginx start
    elif [ -x /etc/init.d/nginx ]; then
        /etc/init.d/nginx start
    else
        echo "无法启动Nginx: 未找到已知的服务管理器"
        return 1
    fi
}

# 重启Nginx
restart_nginx() {
    if command_exists systemctl; then
        systemctl restart nginx
    elif command_exists service; then
        service nginx restart
    elif [ -x /etc/init.d/nginx ]; then
        /etc/init.d/nginx restart
    else
        echo "无法重启Nginx: 未找到已知的服务管理器"
        return 1
    fi
}

# 主循环监控
while true; do
    # 获取东八区当前小时
    hour=$(TZ='Asia/Shanghai' date +'%H')
    
    # 在每天早上7点或晚上7点重启Nginx
    if [[ "$hour" == "07" || "$hour" == "19" ]]; then
        echo "$(date): 到达东八区的 $hour 点. 正在重启 Nginx 服务..."
        restart_nginx
        if is_nginx_running; then
            echo "$(date): Nginx 已成功重启."
        else
            echo "$(date): 重启 Nginx 失败. 请检查错误日志以获取更多信息."
        fi
        # 避免重复触发，等待60分钟后继续监控
        sleep 3600
        continue
    fi

    # 常规监控Nginx状态
    if is_nginx_running; then
        echo "$(date): Nginx 正在运行."
    else
        echo "$(date): Nginx 未运行. 正在尝试启动..."
        start_nginx
        
        # 等待几秒钟让Nginx启动
        sleep 5
        
        if is_nginx_running; then
            echo "$(date): Nginx 已成功启动."
        else
            echo "$(date): 启动Nginx失败. 请检查错误日志以获取更多信息."
        fi
    fi
    
    # 每5分钟检查一次
    sleep 300
done
EOL

    # 设置执行权限
    chmod +x /usr/local/bin/nginx_monitor.sh

    # 创建systemd服务文件
    cat > /etc/systemd/system/nginx-monitor.service << EOL
[Unit]
Description=Nginx Monitor Service
After=network.target

[Service]
ExecStart=/usr/local/bin/nginx_monitor.sh
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOL

    # 重新加载systemd配置
    systemctl daemon-reload

    # 启用并启动服务
    systemctl enable nginx-monitor.service
    systemctl start nginx-monitor.service

    # 立即检查并启动Nginx（采用同样的检测方式）
    if ! pgrep -f "^nginx: (master|worker) process" >/dev/null 2>&1; then
        echo "检测到 Nginx 未运行，正在启动..."
        if command -v systemctl >/dev/null 2>&1; then
            systemctl start nginx
        elif command -v service >/dev/null 2>&1; then
            service nginx start
        elif [ -x /etc/init.d/nginx ]; then
            /etc/init.d/nginx start
        fi
        
        # 等待几秒确认启动状态
        sleep 5
        if pgrep -f "^nginx: (master|worker) process" >/dev/null 2>&1; then
            echo "Nginx 已成功启动"
        else
            echo "警告：Nginx 启动失败，请检查 Nginx 配置或手动启动"
        fi
    else
        echo "Nginx 已在运行中"
    fi

    echo "Nginx监控服务已成功安装并启动。"
    echo "您可以使用 'systemctl status nginx-monitor.service' 命令检查服务状态。"
}

# 卸载函数
uninstall_nginx_monitor() {
    # 停止并禁用服务
    systemctl stop nginx-monitor.service
    systemctl disable nginx-monitor.service
    
    # 删除服务文件
    rm -f /etc/systemd/system/nginx-monitor.service
    
    # 删除监控脚本
    rm -f /usr/local/bin/nginx_monitor.sh
    
    # 重新加载systemd配置
    systemctl daemon-reload
    
    echo "Nginx监控服务已成功卸载。"
}

# 主菜单
while true; do
    echo "请选择操作："
    echo "1. 安装 Nginx 监控服务"
    echo "2. 卸载 Nginx 监控服务"
    echo "3. 退出"
    read -p "输入选项 (1-3): " choice
    
    case $choice in
        1)
            install_nginx_monitor
            break
            ;;
        2)
            uninstall_nginx_monitor
            break
            ;;
        3)
            echo "退出脚本"
            exit 0
            ;;
        *)
            echo "无效选项，请重新选择"
            ;;
    esac
done

