#!/bin/bash
# Zabbix Agent 安装脚本（全系统 100% 官方源，零兼容报错）
# 策略：所有系统一律官方源 → 最稳、最干净、不挑环境
# 版本：Ubuntu/Debian → 7.0 | CentOS7 → 6.4 | CentOS8+ →7.0

# 核心配置
AUTH_KEY="niteng_zabbix_2026_secure"
ZABBIX_SERVER="idc.niteng.net"

# 只留官方源
OFFICIAL_MIRROR="https://repo.zabbix.com/zabbix"
ZABBIX_PUBKEY_ID="D913219AB5333005"

# 颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 全局变量
OS_TYPE="" OS_MAJOR="" OS_CODENAME=""
PKG_MANAGER="" REPO_FILE="" ZABBIX_VER=""
SERVICE_NAME="zabbix-agent"

debug_print() {
    local ts=$(date +"%Y-%m-%d %H:%M:%S")
    case $1 in
        INFO) echo -e "${BLUE}[$ts] INFO $2${NC}" ;;
        WARN) echo -e "${YELLOW}[$ts] WARN $2${NC}" ;;
        ERROR) echo -e "${RED}[$ts] ERROR $2${NC}" ;;
    esac
}

check_package() {
    local pkg=$1
    if [ "$PKG_MANAGER" = "apt" ]; then
        dpkg -s "$pkg" &>/dev/null
    else
        rpm -q "$pkg" &>/dev/null
    fi
}

# root 检查
[ $UID -ne 0 ] && debug_print ERROR "请用 root 执行" && exit 1

# ===================== 系统识别 =====================
if [ -f /etc/redhat-release ]; then
    OS_TYPE="CentOS"
    OS_MAJOR=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | cut -d. -f1)
    PKG_MANAGER="yum"
    [ "$OS_MAJOR" -ge 8 ] && PKG_MANAGER="dnf"
    REPO_FILE="/etc/yum.repos.d/zabbix.repo"

    if [ "$OS_MAJOR" = "7" ]; then
        ZABBIX_VER="6.4"
    else
        ZABBIX_VER="7.0"
    fi

elif [ -f /etc/debian_version ]; then
    if grep -q '^NAME="Ubuntu"' /etc/os-release; then
        OS_TYPE="Ubuntu"
        OS_CODENAME=$(lsb_release -sc 2>/dev/null || echo "focal")
    else
        OS_TYPE="Debian"
        OS_MAJOR=$(grep -oE '[0-9]+' /etc/debian_version | head -n1)
        case $OS_MAJOR in
            10) OS_CODENAME="buster" ;;
            11) OS_CODENAME="bullseye" ;;
            12) OS_CODENAME="bookworm" ;;
            *) OS_CODENAME="bookworm" ;;
        esac
    fi
    PKG_MANAGER="apt"
    REPO_FILE="/etc/apt/sources.list.d/zabbix.list"
    ZABBIX_VER="7.0"
else
    debug_print ERROR "仅支持 CentOS7+/Debian10+/Ubuntu20+"
    exit 1
fi

# ===================== 清理旧环境 =====================
debug_print INFO "清理旧版本"
if [ "$PKG_MANAGER" = "apt" ]; then
    apt purge -y zabbix-agent zabbix-release &>/dev/null
    apt autoremove -y &>/dev/null
    rm -rf /usr/share/keyrings/zabbix* /etc/zabbix $REPO_FILE &>/dev/null
else
    $PKG_MANAGER remove -y zabbix-agent zabbix-release &>/dev/null
    rm -rf /etc/zabbix $REPO_FILE &>/dev/null
fi
systemctl stop zabbix-agent &>/dev/null || true

# ===================== 安装依赖 =====================
debug_print INFO "安装基础依赖"
if [ "$PKG_MANAGER" = "apt" ]; then
    apt update >/dev/null 2>&1
    apt install -y wget curl gnupg >/dev/null 2>&1
else
    $PKG_MANAGER install -y wget curl >/dev/null 2>&1
    if [ "$OS_MAJOR" = "7" ]; then
        $PKG_MANAGER install -y epel-release >/dev/null 2>&1
    fi
fi

# ===================== 配置官方源 =====================
debug_print INFO "配置 Zabbix 官方源"

if [ "$PKG_MANAGER" = "apt" ]; then
    mkdir -p /usr/share/keyrings
    gpg --keyserver keyserver.ubuntu.com --recv-keys $ZABBIX_PUBKEY_ID >/dev/null 2>&1
    gpg --export $ZABBIX_PUBKEY_ID | gpg --dearmor --yes -o /usr/share/keyrings/zabbix.gpg

    if [ "$OS_TYPE" = "Ubuntu" ]; then
        REPO_LINE="deb [signed-by=/usr/share/keyrings/zabbix.gpg] ${OFFICIAL_MIRROR}/${ZABBIX_VER}/ubuntu ${OS_CODENAME} main"
    else
        REPO_LINE="deb [signed-by=/usr/share/keyrings/zabbix.gpg] ${OFFICIAL_MIRROR}/${ZABBIX_VER}/debian ${OS_CODENAME} main"
    fi
    echo "$REPO_LINE" > $REPO_FILE
    apt update || { debug_print ERROR "apt 更新失败"; exit 1; }

else
    rpm --import https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-A14FE591 >/dev/null 2>&1
    cat > $REPO_FILE << EOF
[zabbix]
name=Zabbix Official ${ZABBIX_VER}
baseurl=${OFFICIAL_MIRROR}/${ZABBIX_VER}/rhel/${OS_MAJOR}/x86_64/
enabled=1
gpgcheck=1
gpgkey=https://repo.zabbix.com/RPM-GPG-KEY-ZABBIX-A14FE591
EOF
    $PKG_MANAGER makecache >/dev/null 2>&1
fi

# ===================== 安装 Zabbix Agent =====================
debug_print INFO "安装 Zabbix Agent"
if [ "$PKG_MANAGER" = "apt" ]; then
    apt install -y zabbix-agent --fix-missing >/dev/null 2>&1
else
    $PKG_MANAGER install -y zabbix-agent >/dev/null 2>&1
fi

# ===================== 兜底用户与目录 =====================
id -u zabbix &>/dev/null || useradd -r -s /sbin/nologin zabbix
mkdir -p /etc/zabbix /var/run/zabbix /var/log/zabbix

# ===================== 配置文件 =====================
LOCAL_HOSTNAME=$(hostname)
LOCAL_IP=$(ip route get 223.6.6.6 2>/dev/null | awk '{print $7;exit}' || ip -4 addr | grep -v 127.0.0.1 | grep -oP '\d+(\.\d+){3}' | head -n1)
HOSTNAME_FINAL="${LOCAL_HOSTNAME}_${LOCAL_IP}"

cat > /etc/zabbix/zabbix_agentd.conf << EOF
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
Server=${ZABBIX_SERVER}
ServerActive=${ZABBIX_SERVER}:10051
Hostname=${HOSTNAME_FINAL}
HostMetadata=${AUTH_KEY}
User=zabbix
Include=/etc/zabbix/zabbix_agentd.d/*.conf
EOF

chown -R zabbix:zabbix /etc/zabbix /var/run/zabbix /var/log/zabbix

# ===================== 启动服务 =====================
systemctl daemon-reload >/dev/null 2>&1
systemctl restart zabbix-agent
systemctl enable zabbix-agent >/dev/null 2>&1

if systemctl is-active --quiet zabbix-agent; then
    echo -e "\n${GREEN}✅ Zabbix Agent 安装成功（官方源）${NC}"
    echo "主机名：$HOSTNAME_FINAL"
    echo "配置文件：/etc/zabbix/zabbix_agentd.conf"
else
    debug_print ERROR "启动失败"
    systemctl status zabbix-agent -l
    exit 1
fi


