#!/bin/sh -e

. /usr/lib/s6-policy-common/lib/svctl-common.sh

# The WANTED state, as a word of its own.
#
# Until 1.0.9 this was the answer of "svctl isup" -- and because it was called
# "isup", everybody read it as the actual state. On dns-1 it said "service pdns
# is running" while no pdns_server process existed. The separation is in the
# name now: "isup" asks the supervisor, "iswanted" asks s6-rc.
#
# What it is for: to tell whether a service is not running BECAUSE nobody wants
# it, or although it should run. Those are two situations with two causes, and
# a tool that mixes them sends the reader in the wrong direction.

if test -z "$1" ; then
  echo "svctl-iswanted: usage: svctl-iswanted service" 1>&2
  exit 100
fi

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

if ! svctl_load_active; then
  svctl_report_unmeasurable
  exit 5
fi

if s6-rc-db list services | grep -qFx "$1" || s6-rc-db list bundles | grep -qFx "$1" ; then
  if svctl_is_active "$1"; then
    echo "service $1 is wanted up (s6-rc considers it active)"
    exit 0
  fi
  echo "service $1 is not wanted up"
  exit 3
fi

echo "svctl-iswanted: unknown atomic service: $1" 1>&2
exit 4
