#/bin/bash
# 文件名：zabbix-agent_install.sh
# 功能: zabbix agent 自动安装脚本

USER=zabbix                                         # zabbix 运行用户
CPU_CORE=$(grep -c 'processor' /proc/cpuinfo)       # CPU 核数
ZBX_SER_VER="3.0.1"                                 # zabbix 版本
ZBX_SER_ADR="monitor.wy.net"                        # zabbix 服务器地址
AGENT_NAME="$1"                                     # zabbix agent 节点名称


# 仅 root 用户下运行
if [[ $UID != "0" ]]; then
    echo "Error: Please use root role to run me!"
    exit 67
fi

# 判断 $AGENT_NAME 是否有值存在，否则退出
if [[ -z $AGENT_NAME ]]; then
    echo "Error: Variable $AGENT_NAME is null."
    exit 1
fi

# 创建 zabbix 用户
id -u $USER>/dev/null 2>&1
if [[ $? -ne 0 ]]
then
	groupadd -g 2000 $USER
	useradd -g 2000 -u 2000 -M -s /sbin/nologin $USER
else
	echo "Zabbix user already exists,don't need to create"
fi

yum install -y make gcc \
libxml2-devel net-snmp-devel net-snmp-utils unixODBC-devel \
libssh2-devel glibc-static pcre-devel OpenIPMI-devel \
openssl-devel gnutls-devel openldap-devel curl-devel libcurl-devel


wget -c http://down.vqiu.cn/package/tarball/zabbix/zabbix-${ZBX_SER_VER}.tar.gz
tar axvf zabbix-${ZBX_SER_VER}.tar.gz
cd zabbix-${ZBX_SER_VER}
./configure \
--prefix=/usr/local/${ZBX_SER_VER} \
--enable-agent \
--enable-ipv6 \
--with-openssl \
--with-ldap \
--with-net-snmp \
--with-libcurl \
--with-libxml2 \
--with-ssh2 \
--with-openipmi
make -j$CPU_CORE;make install

# 创建软件链接
ln -svf /usr/local/${ZBX_SER_VER} /usr/local/zabbix

# 复制配制文件
mkdir /etc/zabbix
\cp -r ./conf/* /etc/zabbix
chown -R $USER:$USER /etc/zabbix/

### zabbix-agentd.conf 配置
# 允许执行命令
sed -i "s/.*EnableRemoteCommands=.*/EnableRemoteCommands=1/" /etc/zabbix/zabbix_agentd.conf 
# zabbix server 地址
sed -i "s/Server=.*/Server=${ZBX_SERVER_ADR}/" /etc/zabbix/zabbix_agentd.conf 
sed -i "s/ServerActive=.*/Server=${ZBX_SERVER_ADR}/" /etc/zabbix/zabbix_agentd.conf 
# 当前监控节点名称
sed -i "s/Hostname=.*/Hostname=$1" /etc/zabbix/zabbix_agentd.conf 
# 允许自定义 zabbix 监控项
sed -i "s/UnsafeUserParameters=0/UnsafeUserParameters=1/" /etc/zabbix/zabbix_agentd.conf
 
# 设置环境变量
echo "export PATH=\$PATH:/usr/local/zabbix/sbin:/usr/local/zabbix/bin" > /etc/profile.d/zabbix.sh

cat > /lib/systemd/system/zabbix-agent.service << 'EOF'
[Unit]
Description=Zabbix Agent
After=syslog.target
After=network.target

[Service]
Environment="CONFFILE=/etc/zabbix/zabbix_agentd.conf"
EnvironmentFile=-/etc/sysconfig/zabbix-agent
Type=forking
Restart=always
PIDFile=/tmp/zabbix_agentd.pid
KillMode=process
ExecStart=/usr/local/zabbix/sbin/zabbix_agentd -c $CONFFILE

[Install]
WantedBy=multi-user.target
EOF

systemctl enable zabbix-agent
systemctl start zabbix-agent
