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

mode="${1:-}"
arg="${2:-}"

case "$mode" in
    os_release)
        if [[ -r /etc/os-release ]]; then
            . /etc/os-release
            printf '%s\n' "${PRETTY_NAME:-${NAME:-NiceOS}}"
        else
            echo "unknown"
        fi
        ;;

    updates)
        # tdnf returns 100 when updates are available on some implementations.
        out="$(mktemp)"
        trap 'rm -f "$out"' EXIT
        set +e
        tdnf -q check-update >"$out" 2>/dev/null
        rc=$?
        set -e
        # Count package-looking lines, excluding headings/noise.
        awk '
            NF >= 2 && $1 !~ /^(Refreshing|Metadata|Obsoleting|Security|Available|Last)$/ &&
            $1 !~ /^[-=]+$/ {n++}
            END {print n+0}
        ' "$out"
        exit 0
        ;;

    repo_health)
        if tdnf -q makecache >/dev/null 2>&1; then echo 1; else echo 0; fi
        ;;

    reboot_required)
        # NiceOS kernel update heuristic: running kernel differs from newest
        # installed /boot vmlinuz version. Falls back to 0 if not detectable.
        running="$(uname -r)"
        newest="$(ls -1 /boot/vmlinuz-* 2>/dev/null | sed 's#.*/vmlinuz-##' | sort -V | tail -n1 || true)"
        if [[ -n "$newest" && "$newest" != "$running" ]]; then echo 1; else echo 0; fi
        ;;

    component)
        [[ -n "$arg" ]] || { echo 0; exit 0; }
        if systemctl is-active --quiet "${arg}.service" 2>/dev/null || \
           systemctl is-active --quiet "$arg" 2>/dev/null; then
            echo 1
        else
            echo 0
        fi
        ;;

    tls_days)
        cert="/etc/nice-monitoring/tls/server.crt"
        [[ -r "$cert" ]] || { echo 0; exit 0; }
        end="$(openssl x509 -enddate -noout -in "$cert" | cut -d= -f2-)"
        end_epoch="$(date -d "$end" +%s 2>/dev/null || echo 0)"
        now="$(date +%s)"
        if (( end_epoch <= now )); then echo 0; else echo $(( (end_epoch-now) / 86400 )); fi
        ;;

    postgresql_bytes)
        if [[ -r /etc/nice-monitoring/secrets.env ]]; then
            . /etc/nice-monitoring/secrets.env
        fi
        PGPASSWORD="${DB_PASSWORD:-}" /usr/pgsql/16/bin/psql \
            -h 127.0.0.1 -U zabbix -d zabbix -Atqc \
            "SELECT pg_database_size('zabbix')" 2>/dev/null || echo 0
        ;;

    clickhouse_bytes)
        clickhouse-client --query \
          "SELECT coalesce(sum(total_bytes),0) FROM system.tables WHERE database='zabbix'" \
          2>/dev/null || echo 0
        ;;

    clickhouse_rows)
        clickhouse-client --query \
          "SELECT coalesce(sum(total_rows),0) FROM system.tables WHERE database='zabbix' AND name LIKE 'history%'" \
          2>/dev/null || echo 0
        ;;

    failed_units)
        systemctl --failed --no-legend --no-pager 2>/dev/null | awk 'NF {n++} END {print n+0}'
        ;;

    *)
        echo "Unsupported metric" >&2
        exit 1
        ;;
esac
