#!/bin/bash
UNIT="${1:?usage: check_systemd_unit <unit>}"
ACTIVE=$(systemctl show -p ActiveState --value "$UNIT" 2>/dev/null)
SUB=$(systemctl show -p SubState --value "$UNIT" 2>/dev/null)
RESULT=$(systemctl show -p Result --value "$UNIT" 2>/dev/null)
MEM=$(systemctl show -p MemoryCurrent --value "$UNIT" 2>/dev/null)
[ "$MEM" = "[not set]" ] || [ -z "$MEM" ] && MEM=0

# Detect a corresponding .timer that triggers this unit. If one exists and is
# active, treat the unit as healthy as long as its last run Result=success.
TIMER_NAME=""
case "$UNIT" in
  *.timer|*.socket|*.target|*.mount|*.path) ;;
  *)
    SHORT="${UNIT%.service}"
    if systemctl list-unit-files "${SHORT}.timer" 2>/dev/null | grep -q "${SHORT}.timer"; then
      TIMER_NAME="${SHORT}.timer"
    fi
    ;;
esac

if [ -n "$TIMER_NAME" ]; then
  TIMER_ACTIVE=$(systemctl show -p ActiveState --value "$TIMER_NAME" 2>/dev/null)
  if [ "$TIMER_ACTIVE" != "active" ]; then
    echo "CRITICAL: timer $TIMER_NAME is $TIMER_ACTIVE (last Result=$RESULT) | mem=${MEM}B"; exit 2
  fi
  if [ "$RESULT" = "success" ] || [ -z "$RESULT" ]; then
    echo "OK: $UNIT triggered by $TIMER_NAME, last Result=success | mem=${MEM}B"; exit 0
  fi
  echo "CRITICAL: $UNIT last Result=$RESULT (timer $TIMER_NAME active) | mem=${MEM}B"; exit 2
fi

case "$ACTIVE" in
  active)               echo "OK: $UNIT is $ACTIVE ($SUB) | mem=${MEM}B"; exit 0;;
  activating|reloading) echo "WARNING: $UNIT is $ACTIVE ($SUB) | mem=${MEM}B"; exit 1;;
  *)                    echo "CRITICAL: $UNIT is $ACTIVE ($SUB, Result=$RESULT) | mem=${MEM}B"; exit 2;;
esac
