#!/bin/sh -e

if ! test -L /run/s6-rc/compiled ; then
  echo "svctl-liststate: fatal: s6-rc is not running" 1>&2
  exit 2
fi

dbx="s6-rc-db -c /run/s6-rc/compiled"

{
  # E1 (1.2.0): fuer Longruns am SUPERVISOR messen, nicht nur s6-rc fragen.
  #
  # Bis 1.1.3 hat diese Zeile an jeden aktiven Dienst blind "/up" gehaengt --
  # "aktiv" ist aber der Wunsch der s6-rc-Live-Datenbank und nicht der Zustand des
  # Prozesses. Gemessen auf infra-1 am 24.09.2026, 08:02 UTC: liststate sagte
  # "svc-ctrl up", s6-svstat sagte "down (exitcode 1) 515 seconds". Und svctl-apply
  # schickt den Leser im Fehlerfall genau hierher.
  #
  # Dieselbe Unterscheidung wie in svctl-isup 1.1.0, mit denselben Worten: ein
  # Dienst, den s6-rc oben haben will und der nicht laeuft, heisst hier DOWN und
  # traegt die s6-svstat-Zeile, damit man "langsam" von "tot" unterscheiden kann.
  s6-rc -ua list | while read -r _s ; do
    [ -n "$_s" ] || continue
    if [ "$($dbx type "$_s" 2>/dev/null)" != longrun ] ; then
      echo "$_s/up"
      continue
    fi
    _d="/run/s6-rc/servicedirs/$_s"
    if ! [ -d "$_d" ] ; then
      echo "$_s/up"
      continue
    fi
    _u=$(s6-svstat -o up "$_d" 2>/dev/null) || {
      echo "$_s/up (NICHT MESSBAR: s6-svstat gab keine Antwort)"
      continue
    }
    if [ "$_u" = true ] ; then
      echo "$_s/up"
    else
      echo "$_s/DOWN, obwohl s6-rc ihn als aktiv fuehrt: $(s6-svstat "$_d" 2>/dev/null | tr -d '/')"
    fi
  done
  s6-rc -da list | sed 's|$|/down|'
  # unfortunately pipelines are bundles and can be custom named, currently they all end by convention with "-pipeline"
  $dbx list bundles | grep -Fv -- "-pipeline" | while read -r bundle; do
    # if any service in the bundle is down, the bundle is down, otherwise up
    $dbx contents "$bundle" | while read -r service; do
      if ! s6-rc -a list | grep -qFx "$service"; then
        echo "$bundle/down"
        break 2
      fi
    done
    echo "$bundle/up"
  done
} | sort -d -k1,1 -t/ | column -ts/
