#!/usr/bin/env bash
#
# CheckMK local check: mailpiler (Community Edition, systemd)
#
#   ohne Parameter : erzeugt <<<local:sep(0)>>> Output
#   --detect       : exit 0 = Plugin wird auf dieser Maschine benoetigt
#
# Benoetigt: bash, systemctl, mysql- bzw. mariadb-client, git oder curl;
#            optional dpkg/apt-cache (Paketvergleich), pgrep
# Netz:      github.com (Upstream-Version)
#
# Achtung: kein "set -e" - viele Aufrufe duerfen fehlschlagen, ohne dass das
# Plugin abbricht. Fehler werden pro Service in einen Status uebersetzt.
set -uo pipefail
# Fehlermeldungen von git/curl/mysql werden auf Klartext abgebildet - das
# geht nur mit englischen Meldungen.
export LC_ALL=C LANG=C

########################### Konfiguration ##################################
PILER_UNITS="${PILER_UNITS:-piler piler-smtp pilersearch}"

# Leer lassen = automatisch suchen. Die Legacy-Installation (Quellbau, meist
# vor 1.4.5) liegt unter /usr/local, das Paket unter /etc.
PILER_CONF="${PILER_CONF:-}"
PILER_CONF_CANDIDATES="${PILER_CONF_CANDIDATES:-/etc/piler/piler.conf /usr/local/etc/piler/piler.conf}"

# Legacy-Installation: eigener Status, per Default WARN.
LEGACY_STATE="${LEGACY_STATE:-1}"

# Gleichzeitig laufende Checks. 1 = seriell.
MAX_PARALLEL="${MAX_PARALLEL:-$(nproc 2>/dev/null || echo 4)}"

# Archivierung: Alter der juengsten archivierten Mail.
# Die Defaults sind bewusst hoch: ein Firmenarchiv bekommt uebers Wochenende
# keine Mail, 48h wuerden am Sonntag falsch alarmieren. Die saubere Loesung
# fuer Nacht und Wochenende ist eine CheckMK-Zeitperiode, nicht ein noch
# groesserer Schwellwert hier.
ARCHIVE_WARN_HOURS="${ARCHIVE_WARN_HOURS:-24}"
ARCHIVE_CRIT_HOURS="${ARCHIVE_CRIT_HOURS:-72}"

# Update-Quellen
PILER_PKG="${PILER_PKG:-piler}"
PILER_GIT_REPO="${PILER_GIT_REPO:-https://github.com/jsuto/piler}"
PILER_GIT_API="${PILER_GIT_API:-https://api.github.com/repos/jsuto/piler/releases/latest}"
# Paketquelle: gebaut aus gitlab.bashclub.org/bashclub/piler, veroeffentlicht
# auf apt.bashclub.org. Massgeblich ist hier der apt-Cache, weil nur der sagt,
# was tatsaechlich installierbar ist.
# Nach diesem String wird in der Herkunftsspalte von "apt-cache madison"
# gefiltert, damit nur Pakete aus dem eigenen Repo zaehlen.
# Paketquelle: gebaut aus https://gitlab.bashclub.org/bashclub/piler,
# ausgeliefert ueber apt.bashclub.org.
PILER_REPO_MATCH="${PILER_REPO_MATCH:-apt.bashclub.org}"
GIT_TIMEOUT="${GIT_TIMEOUT:-20}"

# Erste Version, die als Paket ausgeliefert wurde. Aeltere Installationen sind
# zwangslaeufig Quellbau - das erklaert eine Legacy-Installation im Text.
PILER_PKG_SINCE="${PILER_PKG_SINCE:-1.4.5}"

# Lokale Aufrufe (systemctl, apt-cache). Antworten normal in Millisekunden;
# 10s reichen auch auf einem ausgelasteten Host. Haengt dbus/systemd, soll das
# Plugin trotzdem fertig werden und UNKNOWN melden statt zu blockieren.
CMD_TIMEOUT="${CMD_TIMEOUT:-10}"

########################### Helfer #########################################

have() { command -v "$1" >/dev/null 2>&1; }

# timeout startet nur externe Binaries - systemctl ist eins.
sc() { timeout "$CMD_TIMEOUT" systemctl "$@" </dev/null; }

emit() {  # <state> <servicename> <perfdata|-> <text>
  local state="$1" name="$2" perf="${3:--}" text="$4"
  name="${name//\"/}"; name="${name//$'\t'/ }"
  text="${text//$'\n'/ }"; text="${text//$'\t'/ }"
  printf '%s "%s" %s %s\n' "$state" "$name" "$perf" "$text"
}

# Installationshinweis passend zum Paketsystem dieses Hosts.
pkg_hint() {  # <debian-paket> [rpm-paket] [suse-paket]
  local deb="$1" rpm="${2:-$1}" suse="${3:-${2:-$1}}" h
  if   have apt-get; then h="apt install $deb"
  elif have dnf;     then h="dnf install $rpm"
  elif have yum;     then h="yum install $rpm"
  elif have zypper;  then h="zypper install $suse"
  elif have apk;     then h="apk add $deb"
  else h="Paket $deb installieren"
  fi
  # Im Container (container-apps) ist eine Installation beim naechsten
  # Neuaufbau weg - der Hinweis muss aufs Image zielen.
  [[ -n "${CMK_IN_CONTAINER:-}" ]] && h="im Container-Image ergaenzen ($h) bzw. ein Image mit diesem Werkzeug verwenden"
  printf '%s' "$h"
}

# Grund zu einem Exit-Code von timeout/Shell.
rc_reason() {  # <rc> [timeout-sekunden]
  case "$1" in
    124|137) printf 'Zeitlimit %ss ueberschritten' "${2:-$CMD_TIMEOUT}" ;;
    126)     printf 'nicht ausfuehrbar' ;;
    127)     printf 'Programm nicht gefunden' ;;
    *)       printf 'Exit %s' "$1" ;;
  esac
}

# Aussagekraeftigste Zeile einer Werkzeugausgabe (Fehlerzeile bevorzugt).
first_err() {  # <text>
  local t l
  t="$(printf '%s\n' "$1" | sed -E 's/\x1b\[[0-9;]*[A-Za-z]//g; s/^[[:space:]]+//; s/[[:space:]]+$//' | grep -v '^$')"
  l="$(grep -m1 -iE 'error|fatal|denied|refused|not found|no such|failed|unable|cannot|could not|timed? ?out' <<< "$t")"
  [[ -n "$l" ]] || l="$(head -n1 <<< "$t")"
  printf '%s' "${l:0:200}"
}

# Versionsvergleich $1 > $2. dpkg kennt Debian-Revisionen und Epochen; auf
# RPM-Systemen fehlt es - ohne Rueckfall waere dort jeder Vergleich falsch
# und "Piler Update" meldete immer OK.
ver_gt() {  # <a> <b>
  if have dpkg; then
    dpkg --compare-versions "$1" gt "$2" 2>/dev/null
    return
  fi
  [[ "$1" != "$2" ]] && [[ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" == "$1" ]]
}

# Wert aus piler.conf. Kommentare beginnen dort am Zeilenanfang mit '#',
# der Wert selbst reicht bis Zeilenende - ein '#' im Passwort darf ihn also
# nicht abschneiden.
piler_conf() {  # $1 = key
  sed -nE "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*(.*)\$/\1/p" "$PILER_CONF" 2>/dev/null \
    | tail -n1 | sed -E "s/[[:space:]]+\$//; s/^\"(.*)\"\$/\1/; s/^'(.*)'\$/\1/"
}

# Setzt PILER_CONF, falls nicht vorgegeben.
resolve_conf() {
  local c
  [[ -n "$PILER_CONF" ]] && return 0
  for c in $PILER_CONF_CANDIDATES; do
    [[ -r "$c" ]] && { PILER_CONF="$c"; return 0; }
  done
  PILER_CONF="${PILER_CONF_CANDIDATES%% *}"
}

# Setzt INSTALL_TYPE und INSTALL_PREFIX.
#   paket  - Debian-Paket aus dem apt-Repo
#   legacy - Quellbau unter /usr/local (typisch vor 1.4.5)
#   quelle - Quellbau ohne /usr/local-Marker
INSTALL_TYPE="unbekannt"
INSTALL_PREFIX=""
detect_install() {
  if have dpkg-query && dpkg-query -W -f='${Version}' "$PILER_PKG" >/dev/null 2>&1; then
    INSTALL_TYPE="paket"; INSTALL_PREFIX="/usr"; return 0
  fi
  # /usr/sbin/piler ist bei Legacy nur ein Symlink nach /usr/local/sbin -
  # unterschieden wird deshalb ueber die /usr/local-Marker, nicht ueber /usr.
  if [[ -x /usr/local/sbin/piler || -f /usr/local/etc/piler/piler.conf ]]; then
    INSTALL_TYPE="legacy"; INSTALL_PREFIX="/usr/local"; return 0
  fi
  if [[ -x /usr/sbin/piler || -x /usr/bin/piler ]]; then
    INSTALL_TYPE="quelle"; INSTALL_PREFIX="/usr"
  fi
  return 0
}

########################### detect mode ####################################

resolve_conf
detect_install

if [[ "${1:-}" == "--detect" ]]; then
  # Im Container (container-apps) gibt es kein systemd - dort reichen die
  # Dateimarker, die Dienstpruefung faellt auf die Prozesssuche zurueck.
  have systemctl || [[ -n "${CMK_IN_CONTAINER:-}" ]] || exit 1
  [[ -f "$PILER_CONF" ]] && exit 0
  [[ -f /usr/local/etc/piler/piler.conf || -x /usr/local/sbin/piler ]] && exit 0
  sc list-unit-files piler.service >/dev/null 2>&1 \
    && sc cat piler.service >/dev/null 2>&1 && exit 0
  exit 1
fi

########################### Job-Pool #######################################

SEM_FD=""

pool_init() {
  local fifo i
  (( MAX_PARALLEL > 1 )) || return 1
  fifo="$(mktemp -u)" || return 1
  mkfifo "$fifo" 2>/dev/null || return 1
  exec {SEM_FD}<>"$fifo" || { rm -f "$fifo"; SEM_FD=""; return 1; }
  rm -f "$fifo"
  for (( i = 0; i < MAX_PARALLEL; i++ )); do printf '.' >&"$SEM_FD"; done
  return 0
}

pool_run() {  # <ausgabedatei> <kommando...>
  local out="$1"; shift
  # Eigene Subshell je Check: ein Abbruch (z.B. set -u) beendet nur diesen
  # Check, nicht das Plugin - und das Token wird trotzdem zurueckgegeben,
  # sonst verklemmt der Pool nach MAX_PARALLEL Abbruechen.
  if [[ -z "$SEM_FD" ]]; then ( "$@" ) </dev/null > "$out" 2>/dev/null; return 0; fi
  local tok
  IFS= read -r -n1 -u "$SEM_FD" tok
  { ( "$@" ) </dev/null > "$out" 2>/dev/null; printf '.' >&"$SEM_FD"; } &
}

########################### Dienste ########################################

# "active, aber disabled" ist ein eigener Fehlerfall: der Dienst laeuft jetzt,
# kommt nach einem Reboot aber nicht wieder - und genau das faellt sonst erst
# beim naechsten Neustart auf.
# Prozessname zu einer Unit. pilersearch startet searchd bzw. manticore.
unit_process_running() {  # $1 = unit
  local names="$1" p
  [[ "$1" == "pilersearch" ]] && names="searchd manticore"
  for p in $names; do pgrep -x "$p" >/dev/null 2>&1 && return 0; done
  return 1
}

check_services() {
  local u active enabled
  local total=0 running=0
  local -a dead=() notenabled=() nounit=() noanswer=() nopgrep=()

  for u in $PILER_UNITS; do
    total=$(( total + 1 ))
    active="$(sc is-active "$u.service" 2>/dev/null)"
    enabled="$(sc is-enabled "$u.service" 2>/dev/null)"

    # is-active gibt immer etwas aus ("inactive", "unknown"). Leer heisst:
    # systemctl hat nicht geantwortet (Timeout, dbus) - das ist kein Ausfall
    # des Dienstes, sondern "konnte nicht pruefen".
    if [[ -z "$active" ]]; then
      noanswer+=("$u")
      continue
    fi

    if [[ "$active" == "active" ]]; then
      running=$(( running + 1 ))
      [[ "$enabled" == "enabled" || "$enabled" == "static" || "$enabled" == "indirect" ]] \
        || notenabled+=("$u:${enabled:-unbekannt}")
      continue
    fi

    # Alte Quellinstallationen starten searchd teils ueber rc.searchd statt
    # ueber eine Unit. Eine fehlende Unit bei laufendem Prozess ist ein
    # Konfigurationsunterschied, kein Ausfall - und darf nicht CRIT geben.
    if ! sc cat "$u.service" >/dev/null 2>&1; then
      # Ohne pgrep ist "kein Prozess" nicht feststellbar - das waere ein
      # falscher CRIT.
      if ! have pgrep; then
        nopgrep+=("$u")
        continue
      fi
      if unit_process_running "$u"; then
        nounit+=("$u")
        running=$(( running + 1 ))
      else
        dead+=("$u:keine-unit-kein-prozess")
      fi
      continue
    fi
    dead+=("$u:${active:-unbekannt}")
  done

  local perf="services_running=$running;;;0;$total services_failed=${#dead[@]};;1;0"

  if (( ${#dead[@]} > 0 )); then
    local first="${dead[0]%%:*}" fix
    if [[ "${dead[0]}" == *:keine-unit-kein-prozess ]]; then
      fix="Dienst $first starten (Legacy: rc-Skript) bzw. Unit $first.service einrichten"
    else
      fix="systemctl start $first, Ursache mit journalctl -u $first -n 50 pruefen"
    fi
    emit 2 "Piler Services" "$perf" \
      "CRIT - $running/$total aktiv, nicht aktiv: ${dead[*]} - Abhilfe: $fix"
  elif (( ${#noanswer[@]} > 0 )); then
    emit 3 "Piler Services" "$perf" \
      "UNKNOWN - Dienststatus-Abfrage fehlgeschlagen: systemctl antwortet nicht (Timeout ${CMD_TIMEOUT}s) fuer: ${noanswer[*]} - Abhilfe: systemd/dbus pruefen (systemctl status, journalctl -b)"
  elif (( ${#nopgrep[@]} > 0 )); then
    emit 3 "Piler Services" "$perf" \
      "UNKNOWN - Prozesspruefung fehlgeschlagen: keine Unit und pgrep fehlt fuer: ${nopgrep[*]} - Abhilfe: $(pkg_hint procps procps-ng procps)"
  elif (( ${#notenabled[@]} > 0 || ${#nounit[@]} > 0 )); then
    local hint=""
    (( ${#notenabled[@]} > 0 )) && hint="nicht fuer Autostart aktiviert: ${notenabled[*]} (Abhilfe: systemctl enable ${notenabled[0]%%:*})"
    (( ${#nounit[@]} > 0 )) && hint="${hint:+$hint; }laeuft ohne systemd-Unit: ${nounit[*]}"
    emit 1 "Piler Services" "$perf" "WARN - $running/$total aktiv, $hint"
  else
    emit 0 "Piler Services" "$perf" "OK - alle $total Dienste aktiv und aktiviert"
  fi
}

check_installation() {
  local inst inst_full inst_up legacy_note=""
  inst="$(piler_versions)"; inst_full="${inst%%|*}"; inst_up="$(cut -d'|' -f2 <<< "$inst")"
  # Vor PILER_PKG_SINCE gab es noch kein Paket - das erklaert die Legacy-
  # Installation und gehoert in den Text, damit klar ist, warum sie existiert.
  if [[ -n "$inst_up" ]] && ver_gt "$PILER_PKG_SINCE" "$inst_up"; then
    legacy_note=", aelter als $PILER_PKG_SINCE"
  fi

  case "$INSTALL_TYPE" in
    paket)
      emit 0 "Piler Installation" "-" \
        "OK - Paketinstallation ${PILER_PKG} ${inst_full:-?} (Repo ${PILER_REPO_MATCH})" ;;
    legacy)
      emit "$LEGACY_STATE" "Piler Installation" "-" \
        "Legacy-Quellinstallation unter ${INSTALL_PREFIX} (Version ${inst_up:-unbekannt}${legacy_note}), kein Paket - Migration auf das ${PILER_REPO_MATCH}-Paket empfohlen" ;;
    quelle)
      emit "$LEGACY_STATE" "Piler Installation" "-" \
        "Quellinstallation ohne Paket (Version ${inst_up:-unbekannt}), Updates muessen manuell eingespielt werden" ;;
    *)
      emit 3 "Piler Installation" "-" \
        "UNKNOWN - Installationstyp nicht bestimmbar: weder Paket ${PILER_PKG} noch piler-Binary gefunden - Abhilfe: Installation pruefen bzw. PILER_PKG/PILER_CONF setzen" ;;
  esac
}

########################### Archivierung ###################################

# Fuehrt eine Abfrage aus. Ergebnis in SQL_OUT; bei Fehler rc 1 und
# "Grund - Abhilfe: Schritt" in SQL_ERR. Setzt globale Variablen - deshalb
# direkt aufrufen, nicht in $(...).
SQL_OUT=""; SQL_ERR=""
SQL_TIMEOUT="${SQL_TIMEOUT:-30}"
piler_sql() {  # $1 = query
  local host user pass db sock cli out rc ef
  local -a args=()
  SQL_OUT=""; SQL_ERR=""
  if [[ ! -r "$PILER_CONF" ]]; then
    SQL_ERR="$PILER_CONF nicht lesbar - Abhilfe: Plugin als root ausfuehren bzw. PILER_CONF setzen"
    return 1
  fi
  # MariaDB ab 11 liefert teils nur noch "mariadb" ohne mysql-Symlink.
  if have mysql; then cli=mysql; elif have mariadb; then cli=mariadb; else
    SQL_ERR="mysql-Client fehlt - Abhilfe: $(pkg_hint default-mysql-client mariadb mariadb-client)"
    return 1
  fi
  user="$(piler_conf mysqluser)"; pass="$(piler_conf mysqlpwd)"
  db="$(piler_conf mysqldb)";     sock="$(piler_conf mysqlsocket)"
  host="$(piler_conf mysqlhost)"
  if [[ -z "$user" || -z "$db" ]]; then
    SQL_ERR="mysqluser/mysqldb fehlen in $PILER_CONF - Abhilfe: Eintraege in $PILER_CONF pruefen"
    return 1
  fi
  if [[ -n "$sock" ]]; then args=(--socket="$sock"); else args=(-h"${host:-localhost}"); fi
  # Passwort per Umgebungsvariable, nicht als Argument - sonst steht es in
  # der Prozessliste. stderr getrennt einfangen: eine Warnung darf nicht als
  # Ergebniszeile geparst werden.
  ef="$(mktemp)" || ef=/dev/null
  out="$(MYSQL_PWD="$pass" timeout "$SQL_TIMEOUT" "$cli" -N -B -u"$user" "${args[@]}" "$db" -e "$1" 2>"$ef" </dev/null)"; rc=$?
  local err=""
  [[ "$ef" != /dev/null ]] && { err="$(head -c 4000 "$ef")"; rm -f "$ef"; }
  if (( rc == 0 )); then SQL_OUT="$out"; return 0; fi
  case "$err" in
    *"Access denied"*)
      SQL_ERR="Zugang fuer $user abgelehnt - Abhilfe: mysqluser/mysqlpwd in $PILER_CONF gegen die DB-Grants pruefen" ;;
    *"Can't connect"*|*"ERROR 2002"*|*"ERROR 2003"*|*"ERROR 2005"*)
      SQL_ERR="DB-Server ${sock:-${host:-localhost}} nicht erreichbar - Abhilfe: systemctl status mariadb bzw. mysqlhost/mysqlsocket in $PILER_CONF pruefen" ;;
    *"Unknown database"*)
      SQL_ERR="Datenbank $db existiert nicht - Abhilfe: mysqldb in $PILER_CONF pruefen" ;;
    *"doesn't exist"*)
      SQL_ERR="$(first_err "$err") - Abhilfe: piler-Schema pruefen (Tabelle metadata fehlt)" ;;
    *)
      if [[ "$rc" == "124" || "$rc" == "137" || -z "$err" ]]; then
        SQL_ERR="$(rc_reason "$rc" "$SQL_TIMEOUT") - Abhilfe: Last/Locks der Datenbank pruefen (SHOW PROCESSLIST)"
      else
        SQL_ERR="$(first_err "$err") - Abhilfe: Abfrage manuell mit $cli pruefen"
      fi ;;
  esac
  return 1
}

check_archiving() {
  local row newest last24 total age_h now
  if ! piler_sql "
    SELECT COALESCE(MAX(arrived),0),
           COALESCE(SUM(arrived >= UNIX_TIMESTAMP()-86400),0),
           COUNT(*)
    FROM metadata"; then
    emit 3 "Piler Archiving" "-" "UNKNOWN - Datenbankabfrage fehlgeschlagen: $SQL_ERR"
    return 0
  fi
  row="$SQL_OUT"

  IFS=$'\t' read -r newest last24 total <<< "${row:-}"
  # Nur Zahlen weiterreichen - ein unerwarteter Wert wuerde in der
  # Arithmetik unten unter "set -u" als Variablenname abbrechen.
  if ! [[ "${total:-}" =~ ^[0-9]+$ && "${newest:-}" =~ ^[0-9]+$ && "${last24:-}" =~ ^[0-9]+$ ]]; then
    emit 3 "Piler Archiving" "-" \
      "UNKNOWN - Datenbankabfrage lieferte kein auswertbares Ergebnis: $(first_err "${row:-leer}") - Abhilfe: Abfrage manuell pruefen"
    return 0
  fi
  if [[ "${newest:-0}" == "0" ]]; then
    emit 3 "Piler Archiving" "messages_total=$total" \
      "UNKNOWN - noch keine archivierte Mail in der Datenbank - Abhilfe: Mailfluss zum piler (SMTP/Journaling) pruefen"
    return 0
  fi

  now="$(date +%s)"
  age_h=$(( (now - newest) / 3600 ))

  local state=0 txt="OK"
  if   (( age_h >= ARCHIVE_CRIT_HOURS )); then state=2; txt="CRIT"
  elif (( age_h >= ARCHIVE_WARN_HOURS )); then state=1; txt="WARN"
  fi

  emit "$state" "Piler Archiving" \
    "last_mail_age=$age_h;$ARCHIVE_WARN_HOURS;$ARCHIVE_CRIT_HOURS;0 mails_24h=$last24 messages_total=$total" \
    "$txt - juengste Mail vor ${age_h}h ($(date -d "@$newest" '+%Y-%m-%d %H:%M' 2>/dev/null)), $last24 in 24h, $total insgesamt"
}

########################### Installationsart ###############################

# Versionsermittlung. Die Installationsart steht bereits in INSTALL_TYPE
# (siehe detect_install), hier geht es nur noch um die Versionsnummern.
piler_versions() {  # -> "paketversion|upstreamversion|binary"
  local pkgver="" ver="" bin="" b
  if [[ "$INSTALL_TYPE" == "paket" ]] && have dpkg-query; then
    pkgver="$(dpkg-query -W -f='${Version}' "$PILER_PKG" 2>/dev/null)"
    ver="$(sed -E 's/^[0-9]+://; s/-.*$//' <<< "$pkgver")"
  fi

  for b in "${INSTALL_PREFIX}/sbin/piler" "${INSTALL_PREFIX}/bin/piler" \
           /usr/sbin/piler /usr/bin/piler /usr/local/sbin/piler; do
    [[ -x "$b" ]] && { bin="$b"; break; }
  done

  # Ohne Paket bleibt nur das Binary selbst als Versionsquelle.
  if [[ -z "$ver" && -n "$bin" ]]; then
    ver="$(timeout 10 "$bin" -V 2>&1 </dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1)"
    [[ -n "$ver" ]] || ver="$(timeout 10 "$bin" --version 2>&1 </dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -n1)"
  fi

  printf '%s|%s|%s\n' "$pkgver" "$ver" "$bin"
}

########################### Update #########################################

# Netzwerkfehler von git/curl -> Klartext + Abhilfe.
net_reason() {  # <ausgabe> <rc> <ziel>
  local out="$1" rc="$2" url="$3"
  case "$out" in
    *"Could not resolve"*|*"Temporary failure in name resolution"*)
      printf '%s nicht aufloesbar (DNS) - Abhilfe: Namensaufloesung des Hosts pruefen' "$url" ;;
    *"Failed to connect"*|*"Connection timed out"*|*"Connection refused"*|*"Network is unreachable"*|*"Couldn't connect"*)
      printf '%s - Abhilfe: Zugriff auf %s (Port 443) in der Firewall freigeben bzw. https_proxy setzen' "$(first_err "$out")" "$url" ;;
    *"SSL"*|*"certificate"*)
      printf '%s - Abhilfe: CA-Zertifikate aktualisieren (%s) bzw. TLS-Proxy pruefen' "$(first_err "$out")" "$(pkg_hint ca-certificates)" ;;
    *"403"*|*"rate limit"*)
      printf 'github-API verweigert (Rate-Limit?) - Abhilfe: git installieren (%s), ls-remote unterliegt keinem API-Limit' "$(pkg_hint git)" ;;
    *"could not read Username"*|*"Authentication failed"*|*"not found"*|*"404"*)
      printf '%s - Abhilfe: PILER_GIT_REPO/PILER_GIT_API pruefen (Repo umgezogen?)' "$(first_err "$out")" ;;
    *)
      if [[ "$rc" == "124" || "$rc" == "137" || -z "$out" ]]; then
        printf '%s - Abhilfe: Erreichbarkeit von %s pruefen (Firewall/Proxy), ggf. GIT_TIMEOUT erhoehen' "$(rc_reason "$rc" "$GIT_TIMEOUT")" "$url"
      else
        printf '%s - Abhilfe: Erreichbarkeit von %s pruefen (Firewall/Proxy)' "$(first_err "$out")" "$url"
      fi ;;
  esac
}

# Hoechster Release-Tag im piler-Git -> UP_VER; bei Fehler Grund in UP_ERR.
# Setzt globale Variablen - deshalb direkt aufrufen, nicht in $(...).
UP_VER=""; UP_ERR=""
piler_upstream() {
  local out rc
  UP_VER=""; UP_ERR=""
  if have git; then
    # GIT_TERMINAL_PROMPT=0: verlangt das Repo Zugangsdaten (Umzug, privat),
    # fragt git sonst auf dem Terminal nach statt abzubrechen.
    out="$(GIT_TERMINAL_PROMPT=0 timeout "$GIT_TIMEOUT" git ls-remote --tags --refs "$PILER_GIT_REPO" 2>&1 </dev/null)"; rc=$?
    if (( rc == 0 )); then
      UP_VER="$(sed -nE 's#.*refs/tags/piler-([0-9][0-9.]*)$#\1#p' <<< "$out" | sort -V | tail -n1)"
      [[ -n "$UP_VER" ]] || UP_ERR="git ls-remote: keine piler-Tags in $PILER_GIT_REPO - Abhilfe: PILER_GIT_REPO pruefen"
    else
      UP_ERR="git ls-remote fehlgeschlagen: $(net_reason "$out" "$rc" "$PILER_GIT_REPO")"
    fi
  fi
  if [[ -z "$UP_VER" ]] && have curl; then
    out="$(timeout "$GIT_TIMEOUT" curl -fsS --connect-timeout 10 "$PILER_GIT_API" 2>&1 </dev/null)"; rc=$?
    if (( rc == 0 )); then
      UP_VER="$(sed -nE 's/.*"tag_name"[[:space:]]*:[[:space:]]*"piler-([^"]+)".*/\1/p' <<< "$out" | head -n1)"
      [[ -n "$UP_VER" ]] || UP_ERR="${UP_ERR:+$UP_ERR; }github-API: kein piler-Release in der Antwort - Abhilfe: PILER_GIT_API pruefen"
    else
      UP_ERR="${UP_ERR:+$UP_ERR; }curl fehlgeschlagen: $(net_reason "$out" "$rc" "$PILER_GIT_API")"
    fi
  fi
  if [[ -z "$UP_VER" && -z "$UP_ERR" ]]; then
    UP_ERR="weder git noch curl vorhanden - Abhilfe: $(pkg_hint git)"
  fi
  [[ -n "$UP_VER" ]] && UP_ERR=""
  return 0
}

# Hoechste Version des Pakets, die aus dem eigenen Repo verfuegbar ist.
# Gelesen wird der lokale apt-Cache - das Plugin macht bewusst KEIN
# "apt-get update", das gehoert in den apt-Timer des Systems.
# Setzt REPO_VER; REPO_NOTE erklaert, warum das Repo nicht pruefbar ist.
# Setzt globale Variablen - deshalb direkt aufrufen, nicht in $(...).
REPO_VER=""; REPO_NOTE=""
piler_repo_version() {
  local out rc
  REPO_VER=""; REPO_NOTE=""
  # RPM-Systeme: es gibt kein apt-Repo, das man pruefen koennte - das ist
  # kein Fehler, sondern nur ein fehlender Vergleich.
  if ! have apt-cache; then
    REPO_NOTE="kein apt-cache (kein Debian-System), ${PILER_REPO_MATCH}-Repo nicht pruefbar"
    return 0
  fi
  out="$(timeout "$CMD_TIMEOUT" apt-cache madison "$PILER_PKG" 2>/dev/null </dev/null)"; rc=$?
  if (( rc != 0 )); then
    REPO_NOTE="apt-cache madison fehlgeschlagen: $(rc_reason "$rc") - Abhilfe: apt-cache madison $PILER_PKG manuell pruefen"
    return 0
  fi
  REPO_VER="$(awk -F'|' -v m="$PILER_REPO_MATCH" '
        index($3, m) > 0 { gsub(/^[[:space:]]+|[[:space:]]+$/, "", $2); print $2 }' <<< "$out" \
    | sort -V | tail -n1)"
  # Repo gar nicht eingebunden? Dann ist "kein Paket" keine Aussage ueber
  # das Repo, sondern ueber die apt-Quellen dieses Hosts.
  if [[ -z "$REPO_VER" ]] \
     && ! timeout "$CMD_TIMEOUT" apt-cache policy 2>/dev/null </dev/null | grep -qF "$PILER_REPO_MATCH"; then
    REPO_NOTE="${PILER_REPO_MATCH} ist nicht als apt-Quelle eingebunden - Abhilfe: Quelle unter /etc/apt/sources.list.d/ eintragen und apt update"
  fi
  return 0
}

# Wie alt sind die apt-Listen? Ein haengender apt-Timer laesst ein laengst
# veroeffentlichtes Paket unsichtbar werden - der Check meldete dann WARN
# ("noch kein Paket") statt CRIT ("installierbar").
apt_lists_age_days() {
  local newest
  newest="$(stat -c %Y /var/lib/apt/periodic/update-success-stamp 2>/dev/null)"
  if [[ -z "$newest" ]]; then
    newest="$(find /var/lib/apt/lists -maxdepth 1 -type f -name '*Packages*' \
                -printf '%T@\n' 2>/dev/null | sort -n | tail -n1 | cut -d. -f1)"
  fi
  [[ "$newest" =~ ^[0-9]+$ ]] || return 1
  printf '%s\n' $(( ( $(date +%s) - newest ) / 86400 ))
}

check_update() {
  local info typ inst_full inst_up up repo repo_up stale hint=""
  typ="$INSTALL_TYPE"
  info="$(piler_versions)"
  IFS='|' read -r inst_full inst_up _ <<< "$info"
  piler_upstream;     up="$UP_VER"
  piler_repo_version; repo="$REPO_VER"
  [[ -n "$REPO_NOTE" ]] && hint="${hint} [$REPO_NOTE]"
  repo_up="$(sed -E 's/^[0-9]+://; s/-.*$//' <<< "${repo:-}")"

  stale="$(apt_lists_age_days)" || stale=""
  if [[ -n "$stale" ]] && (( stale > 7 )); then
    hint="${hint} [apt-Listen sind $stale Tage alt - Paketstand evtl. veraltet, Abhilfe: apt update bzw. apt-daily.timer pruefen]"
  fi

  if [[ -z "$inst_up" ]]; then
    emit 3 "Piler Update" "-" \
      "UNKNOWN - installierte Version nicht ermittelbar: weder Paket '$PILER_PKG' noch 'piler -V' liefern eine Version - Abhilfe: Installation pruefen bzw. PILER_PKG setzen"
    return 0
  fi
  if [[ -z "$up" ]]; then
    emit 3 "Piler Update" "-" \
      "UNKNOWN - Upstream-Version abrufen fehlgeschlagen: $UP_ERR (installiert $inst_up)"
    return 0
  fi

  local git_newer=0 repo_newer=0
  ver_gt "$up" "$inst_up" && git_newer=1
  if [[ -n "$repo" ]]; then
    if [[ -n "$inst_full" ]]; then
      # Paketinstallation: volle Version vergleichen, damit auch eine reine
      # Paketrevision (1.4.8-1 -> 1.4.8-2) anschlaegt.
      ver_gt "$repo" "$inst_full" && repo_newer=1
    else
      # Legacy/Quellinstallation: es gibt keine Paketrevision zum Vergleichen.
      ver_gt "$repo_up" "$inst_up" && repo_newer=1
    fi
  fi

  local perf="update_upstream=$git_newer;1;;0;1 update_repo=$repo_newer;;1;0;1"

  local shown="${inst_full:-$inst_up}"
  [[ "$typ" == "legacy" ]] && shown="$inst_up (Legacy, kein Paket)"

  if (( repo_newer && git_newer )); then
    emit 2 "Piler Update" "$perf" \
      "CRIT - Update in beiden Quellen verfuegbar, aber nicht installiert: piler-Git $up, ${PILER_REPO_MATCH}-Repo $repo, installiert $shown$hint"
  elif (( repo_newer )); then
    emit 2 "Piler Update" "$perf" \
      "CRIT - Paket-Update im ${PILER_REPO_MATCH}-Repo verfuegbar: $repo, installiert $shown$hint"
  elif (( git_newer )) && [[ -z "$repo" && -n "$REPO_NOTE" ]]; then
    # Repo nicht pruefbar: nicht behaupten, es gebe dort kein Paket.
    emit 1 "Piler Update" "$perf" \
      "WARN - piler $up ist released, installiert $shown$hint"
  elif (( git_newer )); then
    emit 1 "Piler Update" "$perf" \
      "WARN - piler $up ist released, aber noch kein Paket im ${PILER_REPO_MATCH}-Repo (dort: ${repo:-keins}), installiert $shown$hint"
  else
    emit 0 "Piler Update" "$perf" \
      "OK - piler $inst_up ist aktuell (Upstream $up, Repo ${repo:-n/a}), installiert $shown$hint"
  fi
}

########################### Ausgabe sammeln ################################

collect() {
  echo "<<<local:sep(0)>>>"

  if ! have systemctl; then
    emit 2 "Piler" "-" "CRIT - systemctl nicht gefunden - Abhilfe: Plugin setzt systemd voraus, Dienste manuell ueberwachen"
    return 0
  fi

  local tmpdir
  tmpdir="$(mktemp -d)" || return 0
  trap 'rm -rf "$tmpdir"' RETURN

  pool_init || SEM_FD=""

  # Der Update-Check spricht mit github und dominiert die Laufzeit, deshalb
  # laeuft er parallel zu den lokalen Checks.
  pool_run "$tmpdir/01.out" check_installation
  pool_run "$tmpdir/02.out" check_services
  pool_run "$tmpdir/03.out" check_archiving
  pool_run "$tmpdir/04.out" check_update
  wait

  # Bricht ein Check ab, bleibt seine Datei leer und der Service fehlte still.
  local -A expect=( [01]="Piler Installation" [02]="Piler Services"
                    [03]="Piler Archiving"    [04]="Piler Update" )
  local k
  for k in "${!expect[@]}"; do
    [[ -s "$tmpdir/$k.out" ]] || emit 3 "${expect[$k]}" "-" \
      "UNKNOWN - Check fehlgeschlagen: ohne Ausgabe abgebrochen (Timeout oder Shell-Fehler) - Abhilfe: Plugin manuell mit bash -x ausfuehren und Ausgabe pruefen" \
      > "$tmpdir/$k.out"
  done

  local n
  for n in "$tmpdir"/*.out; do
    [[ -s "$n" ]] && cat "$n"
  done
  return 0
}

########################### Main ###########################################

collect

exit 0