#!/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"

{
  s6-rc -ua list | sed 's|$|/up|'
  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/
