#!/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): measure longruns at the SUPERVISOR, not only by asking s6-rc.
  #
  # Until 1.1.3 this line blindly appended "/up" to every active service -- but
  # "active" is the wish of the s6-rc live database, not the state of the
  # process. Measured on infra-1 on 24.09.2026, 08:02 UTC: liststate said
  # "svc-ctrl up", s6-svstat said "down (exitcode 1) 515 seconds". And
  # svctl-apply sends the reader exactly here when something fails.
  #
  # The same distinction as in svctl-isup 1.1.0, with the same words: a service
  # s6-rc wants up that is not running reads DOWN here and carries the s6-svstat
  # line, so that "slow" can be told from "dead".
  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 (NOT MEASURABLE: s6-svstat gave no answer)"
      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
    # 1.3.0: an empty bundle (an anchor nobody has attached to yet) is
    # neither up nor down
    if [ -z "$($dbx contents "$bundle")" ] ; then
      echo "$bundle/empty"
      continue
    fi
    # 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/
