#!/bin/bash

# 带颜色输出的安装脚本
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
RESET='\033[0m'

# 定义版本变量（方便后期维护）
ZABBIX_VERSION="7.0"
UBUNTU_CODENAME="jammy"  # Ubuntu 22.04

check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo -e "${RED}错误：请使用sudo运行此脚本${RESET}"
        exit 1
    fi
}

install_agent() {
    echo -e "${BLUE}[1/5] 正在添加Zabbix仓库...${RESET}"
    deb_url="https://repo.zabbix.com/zabbix/${ZABBIX_VERSION}/ubuntu/pool/main/z/zabbix-release/zabbix-release_latest_${ZABBIX_VERSION}+ubuntu22.04_all.deb"
    
    if ! wget -q "$deb_url"; then
        echo -e "${RED}错误：无法下载仓库包，请检查版本号或网络连接${RESET}"
        exit 1
    fi
    
    if ! dpkg -i zabbix-release_latest_${ZABBIX_VERSION}+ubuntu22.04_all.deb; then
        echo -e "${RED}错误：仓库包安装失败${RESET}"
        exit 1
    fi

    echo -e "${BLUE}[2/5] 正在更新软件源...${RESET}"
    if ! apt update -qq; then
        echo -e "${RED}错误：软件源更新失败${RESET}"
        exit 1
    fi

    echo -e "${BLUE}[3/5] 正在安装zabbix-agent2...${RESET}"
    if ! apt install -y zabbix-agent2; then
        echo -e "${RED}错误：软件包安装失败${RESET}"
        exit 1
    fi

    echo -e "${BLUE}[4/5] 正在配置服务...${RESET}"
    if ! systemctl enable --now zabbix-agent2; then
        echo -e "${RED}错误：服务启动失败${RESET}"
        exit 1
    fi

    echo -e "${BLUE}[5/5] 清理安装包...${RESET}"
    rm -f zabbix-release_latest_${ZABBIX_VERSION}+ubuntu22.04_all.deb
}

show_result() {
    echo -e "\n${GREEN}安装完成！${RESET}"
    echo -e "${YELLOW}后续步骤：${RESET}"
    echo "1. 编辑配置文件：nano /etc/zabbix/zabbix_agent2.conf"
    echo "2. 修改 Server= 和 Hostname= 参数"
    echo "3. 重启服务：systemctl restart zabbix-agent2"
    echo -e "\n服务状态检查：systemctl status zabbix-agent2"
}

main() {
    check_root
    install_agent
    show_result
}

main
