#!/bin/bash

# ==============================================================================
# Zabbix Agent 2 FINAL (Proxmox 6-9) - No More AWK Errors
# ==============================================================================

# --- KONFIGURATION ---
ZABBIX_SERVER="zabbix.bp-techzone.de"
METADATA="proxmox-node"
PSK_ID="psk1"
PSK_KEY="e4f52ba09d969afe1ea5fb7c371f5e50e03014b6c20f7186ff7cf2f900f98a2a"

# --- OS-ERKENNUNG ---
OS_CODENAME=$(lsb_release -sc 2>/dev/null || grep -oP 'VERSION_CODENAME=\K\w+' /etc/os-release)
case "$OS_CODENAME" in
    "buster")  DEB_VER="10" ;;
    "bullseye") DEB_VER="11" ;;
    "bookworm") DEB_VER="12" ;;
    "trixie")   DEB_VER="13" ;;
    *)          DEB_VER="12" ;;
esac

# 1. Repository & Installation
wget -q "https://repo.zabbix.com/zabbix/7.0/debian/pool/main/z/zabbix-release/zabbix-release_latest+debian${DEB_VER}_all.deb" -O /tmp/zabbix-release.deb
dpkg -i /tmp/zabbix-release.deb
apt update && apt install zabbix-agent2 smartmontools -y

# 2. PSK Setup
echo "$PSK_KEY" > /etc/zabbix/zabbix_agent2.psk
chown zabbix:zabbix /etc/zabbix/zabbix_agent2.psk
chmod 600 /etc/zabbix/zabbix_agent2.psk

# 3. Agent Config (Active Only)
sed -i '/^Server=/d; /^ServerActive=/d; /^Hostname=/d; /^HostnameItem=/d; /^HostMetadata=/d; /^TLSConnect=/d; /^TLSAccept=/d; /^TLSPSKIdentity=/d; /^TLSPSKFile=/d' /etc/zabbix/zabbix_agent2.conf
cat <<EOF >> /etc/zabbix/zabbix_agent2.conf
Server=
ServerActive=$ZABBIX_SERVER
HostnameItem=system.hostname[fqdn]
HostMetadata=$METADATA
TLSConnect=psk
TLSAccept=psk
TLSPSKIdentity=$PSK_ID
TLSPSKFile=/etc/zabbix/zabbix_agent2.psk
EOF

# 4. DAS HELFER-SKRIPT (Löst das AWK-Problem)
cat << 'EOF' > /usr/local/bin/zfs-zabbix-stats.sh
#!/bin/bash
zpool list -H -o name,capacity > /tmp/zfs_list.txt
zpool status | awk '$1 !~ /state:/ && $2 ~ /^(ONLINE|DEGRADED|FAULTED|OFFLINE|UNAVAIL|REMOVED)/ {print $1, $2, $3, $4, $5}' > /tmp/zfs_status.txt
awk 'NR==FNR {cap[$1]=$2; next} {printf "{\"name\":\"%s\",\"capacity\":\"%s\",\"health\":\"%s\",\"read\":\"%s\",\"write\":\"%s\",\"cksum\":\"%s\"}\n", $1, (cap[$1]?cap[$1]:"0%"), $2, $3, $4, $5}' /tmp/zfs_list.txt /tmp/zfs_status.txt | awk 'BEGIN {print "["} {if (NR>1) printf ",\n"; print} END {print "]"}'
EOF
chmod +x /usr/local/bin/zfs-zabbix-stats.sh

# 5. Zabbix Custom Parameters
cat << 'EOF' > /etc/zabbix/zabbix_agent2.d/proxmox_custom.conf
UserParameter=custom.zfs.discovery,sudo /usr/sbin/zpool list -H -o name,health,capacity | awk 'BEGIN {print "["} {if (NR>1) printf ",\n"; printf "{\"name\":\"%s\",\"health\":\"%s\",\"capacity\":\"%s\"}", $1, $2, $3} END {print "\n]"}'
UserParameter=custom.zfs.get,sudo /usr/local/bin/zfs-zabbix-stats.sh
UserParameter=proxmox.backup.check,sudo /usr/bin/pvesh get /cluster/backup-info/not-backed-up --output-format json | grep -q "vmid" && echo 0 || echo 1
UserParameter=proxmox.backup.failed,sudo find /var/log/pve/tasks/ -name "UPID:*:vzdump:*" -mmin -1440 -exec grep -l "ERROR" {} + | wc -l
EOF

# 6. Sudoers
cat <<EOF > /etc/sudoers.d/zabbix
zabbix ALL=(ALL) NOPASSWD: /usr/sbin/zpool list *
zabbix ALL=(ALL) NOPASSWD: /usr/sbin/zpool status
zabbix ALL=(ALL) NOPASSWD: /usr/sbin/smartctl *
zabbix ALL=(ALL) NOPASSWD: /usr/local/bin/zfs-zabbix-stats.sh
zabbix ALL=(ALL) NOPASSWD: /usr/bin/pvesh get /cluster/backup-info/not-backed-up --output-format json
zabbix ALL=(ALL) NOPASSWD: /usr/bin/find /var/log/pve/tasks/ -name UPID\:*
zabbix ALL=(ALL) NOPASSWD: /usr/bin/grep -L OK /var/log/pve/tasks/*
EOF
chmod 440 /etc/sudoers.d/zabbix

# 6. Dienst aktivieren und starten
systemctl enable zabbix-agent2
systemctl restart zabbix-agent2

echo "--- Installation abgeschlossen: $(hostname -f) ---"
