#!/usr/bin/env bash
# process_check.sh — service liveness.
#
# A service entity's name is a logical label, rarely the literal systemd unit
# or container name. matrix = matrix-synapse.service + element-web/mautrix-*
# containers; authentik = authentik-server/-worker containers. So checking
# `systemctl is-active matrix` reports "inactive" for a healthy service.
#
# Resolution order, any hit = healthy:
#   1. exact systemd unit  `systemctl is-active <name>`
#   2. a systemd unit with the name as prefix  `<name>*.service`
#   3. a running docker container whose name contains <name>
# An explicit probe target overrides the label — see checkdefaults, which
# passes a `probe_unit`/`container`/`systemd_unit` attribute as $1 when set.
set -euo pipefail

SERVICE="${1:-}"
if [ -z "$SERVICE" ]; then
  echo '{"health":"unknown","signalKind":"process-check","evidence":"no service name provided"}'
  exit 0
fi

ok() { echo "{\"health\":\"healthy\"}"; exit 0; }

# 1. exact systemd unit
if command -v systemctl >/dev/null 2>&1; then
  STATE=$(systemctl is-active "$SERVICE" 2>/dev/null | head -1 || true)
  [ "$STATE" = "active" ] && ok

	# 2. prefix match: matrix -> matrix-synapse.service, house -> house.service, etc.
	# --no-legend strips the header/footer so grep can see the unit rows; the
	# pattern is a systemd unit glob.
	if systemctl list-units --type=service --state=active --no-legend "$SERVICE*.service" 2>/dev/null \
       | grep -q '\.service'; then
    ok
  fi
fi

# 3. a running docker container whose name contains the label.
if command -v docker >/dev/null 2>&1; then
  if docker ps --filter "status=running" --filter "name=$SERVICE" --format '{{.Names}}' 2>/dev/null \
       | grep -q .; then
    ok
  fi
fi

STATE=${STATE:-inactive}
STATE=${STATE//\"/}
SAFE_SERVICE=${SERVICE//\"/}
echo "{\"health\":\"degraded\",\"signalKind\":\"process\",\"evidence\":\"$SAFE_SERVICE is $STATE (no active unit/container matched)\"}"
