#!/usr/bin/env bash
set -Eeuo pipefail

tokens=()
add() {
    local t="$1"
    [[ -n "$t" ]] || return 0
    for x in "${tokens[@]:-}"; do
        [[ "$x" != "$t" ]] || return 0
    done
    tokens+=("$t")
}

add "nice=1"
add "os=linux"

arch="$(uname -m 2>/dev/null || true)"
[[ -z "$arch" ]] || add "arch=$arch"

if [[ -r /etc/os-release ]]; then
    # shellcheck disable=SC1091
    . /etc/os-release
    id="${ID:-unknown}"
    id="$(printf '%s' "$id" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9._-')"
    [[ -z "$id" ]] || add "distro=$id"
    if grep -Eqi 'nice[ ._-]?os' /etc/os-release; then
        add "distro=niceos"
    fi
fi

if command -v systemd-detect-virt >/dev/null 2>&1; then
    virt="$(systemd-detect-virt 2>/dev/null || true)"
    [[ -z "$virt" || "$virt" == "none" ]] || add "virt=$virt"
fi

running="$(systemctl list-units --type=service --state=running --no-legend --no-pager 2>/dev/null | awk '{print $1}' || true)"

has_unit() {
    local re="$1"
    grep -Eq "$re" <<<"$running"
}

has_unit '^postgresql(16)?\.service$' && add "svc=postgresql"
has_unit '^(mysqld|mariadb)\.service$' && add "svc=mysql"
has_unit '^nginx\.service$' && add "svc=nginx"
has_unit '^(httpd|apache2)\.service$' && add "svc=apache"
has_unit '^redis(-server)?\.service$' && add "svc=redis"
has_unit '^rabbitmq-server\.service$' && add "svc=rabbitmq"
has_unit '^clickhouse-server\.service$' && add "svc=clickhouse"
has_unit '^haproxy\.service$' && add "svc=haproxy"
has_unit '^keepalived\.service$' && add "svc=keepalived"
has_unit '^kubelet\.service$' && add "svc=kubernetes-node"
has_unit '^etcd\.service$' && add "svc=etcd"
has_unit '^containerd\.service$' && add "runtime=containerd"
has_unit '^docker\.service$' && add "runtime=docker"
has_unit '^libvirtd\.service$' && add "virtstack=libvirt"
has_unit '^prometheus\.service$' && add "svc=prometheus"
has_unit '^grafana-server\.service$' && add "svc=grafana"

command -v podman >/dev/null 2>&1 && add "runtime=podman"
[[ -d /sys/class/nvme ]] && compgen -G '/sys/class/nvme/nvme*' >/dev/null && add "hw=nvme"
[[ -r /proc/driver/nvidia/version ]] && add "gpu=nvidia"
[[ -d /sys/class/infiniband ]] && compgen -G '/sys/class/infiniband/*' >/dev/null && add "net=rdma"

# Keep metadata one-line, deterministic and comfortably below Zabbix limits.
printf '%s;' "${tokens[@]}" | cut -c1-1800
echo
