#!/bin/sh
# Checkmk-Local-Check (bashclub-updates): WARN ohne automatische Updates, wenn
# ein nötiger Neustart nicht automatisch kommt (REBOOT=never) oder die Frist
# (REBOOT_DEADLINE) überschritten ist, der Neustart also trotzdem ausblieb,
# oder wenn dpkg --audit halb installierte bzw. konfigurierte Pakete meldet und
# gerade kein dpkg/apt/unattended-upgrades läuft (dann ist das nur ein Zwischenstand)
service='"OS-Updates"'
AUTO=yes REBOOT=window REBOOT_DEADLINE=7d
# shellcheck source=/dev/null
[ -r /etc/bashclub/updates.conf ] && . /etc/bashclub/updates.conf
needed=$(cat /run/bashclub-updates/reboot-needed 2>/dev/null || true)
since=$(cat /var/lib/bashclub-updates/needed-since 2>/dev/null || true)
case $REBOOT_DEADLINE in
*d) limit=$((${REBOOT_DEADLINE%d} * 86400)) ;;
*h) limit=$((${REBOOT_DEADLINE%h} * 3600)) ;;
*) limit=604800 ;;
esac
# Eine Stunde Spielraum für Fenster und laufendes apt
overdue=no
if [ -n "$needed" ] && [ -n "$since" ] && [ "$(date +%s)" -gt $((since + limit + 3600)) ]; then overdue=yes; fi
# Paketnamen aus dpkg --audit: eingerückte Zeilen unter den Überschriften
audit=$(dpkg --audit 2>/dev/null | sed -n 's/^ \([a-z0-9][^ ]*\).*/\1/p' | LC_ALL=C sort -u)
busy=no
if [ -n "$audit" ] && pgrep -x 'dpkg|apt|apt-get|unattended-upgr' >/dev/null 2>&1; then busy=yes; fi
if [ -n "$audit" ] && [ "$busy" = no ]; then
	count=$(printf '%s\n' "$audit" | wc -l)
	first=$(printf '%s\n' "$audit" | head -n 3 | tr '\n' ' ')
	first=${first% }
	[ "$count" -gt 3 ] && first="$first …"
	echo "1 $service - dpkg unvollständig: $count Paket(e): $first – Abhilfe: dpkg --configure -a"
elif [ "$AUTO" != yes ]; then
	echo "1 $service - Updates nicht automatisch (AUTO=$AUTO)"
elif [ -n "$needed" ] && [ "$REBOOT" = never ]; then
	echo "1 $service - Neustart nötig: $needed (REBOOT=never)"
elif [ "$overdue" = yes ]; then
	echo "1 $service - Neustart überfällig (Frist $REBOOT_DEADLINE): $needed"
elif [ -n "$needed" ]; then
	echo "0 $service - automatisch, Neustart steht an: $needed"
elif [ "$busy" = yes ]; then
	echo "0 $service - automatisch, Paketinstallation läuft"
else
	echo "0 $service - automatisch, REBOOT=$REBOOT"
fi
