#!/bin/sh -e

dbx="s6-rc-db -c /usr/lib/s6-rc/compiled-work"

policy="$(readlink /usr/lib/s6-rc/policy/current)"
if [ "${policy:-}" = "exclusive" ]; then
  top="top"
elif [ "${policy:-}" = "shared" ]; then
  top="runlevel_2"
else
  echo "svctl-listforecast: fatal: /usr/lib/s6-rc/policy/current should be a relative symlink to either shared or exclusive" 1>&2
  exit 100
fi


up="$(mktemp /tmp/svctl-listforecast-up.XXXXXX)"
masked="$(mktemp /tmp/svctl-listforecast-masked.XXXXXX)"
cleanup() {
  rm -f "$up" "$masked"
}
trap cleanup EXIT TERM HUP QUIT INT ABRT

$dbx all-dependencies "$top" > "$up"
ls -1 /usr/lib/s6-rc/masked > "$masked"

{
  sed 's|$|/up|' "$up"
  $dbx list services | grep -vFx -f "$up" -f "$masked" | sed 's|$|/down|'
  sed 's|$|/down/masked|' "$masked"
  # 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 ! grep -qFx "$service" < "$up"; then
        echo "$bundle/down"
        break 2
      fi
    done
    echo "$bundle/up"
  done
} | sort -d -k1,1 -t/ | column -ts/
