#!/bin/sh -e

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

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

policy=$(readlink /usr/lib/s6-rc/policy/current)
if test x"$policy" = x"exclusive" ; then
  isexclusive=true
  top="top"
elif test x"$policy" = x"shared" ; then
  isexclusive=false
  top="runlevel_2"
else
  echo "svctl-mask: fatal: /usr/lib/s6-rc/policy/current should be a relative symlink to either shared or exclusive" 1>&2
  exit 100
fi
 
tmp=$(mktemp /tmp/svctl-mask.XXXXXX)
cleanup () {
  rm -f "$tmp"
}
trap cleanup EXIT TERM INT HUP QUIT ABRT

$dbx -d all-dependencies "$@" > "$tmp"
# "|| true": grep exits 1 when nothing matches, and with "set -e" that ends the
# script right here -- before anything was masked at all. Masking a service that
# is already disabled did nothing and returned 1 (2026-09-22).
todisable=$($dbx contents "$top" | grep -Fx -f "$tmp" || true)

cleanup
trap - EXIT TERM INT HUP QUIT ABRT

if test -n "$todisable" ; then
  echo "svctl-mask: info: disabling the following services: $todisable" 1>&2
  for i in $todisable ; do
    # The enable list lives in <top>/contents.d/<service>, not in <top>/<service>
    # -- see svctl-disable. Until 2026-09-22 these two lines removed a path that
    # never exists, so "svctl mask" masked the service but left it enabled, and
    # Puppet re-masked it on every run.
    if $isexclusive ; then
      rm -f "/usr/lib/s6-rc/policy/exclusive/top/contents.d/$i"
    else
      for j in 2 3 4 5 ; do
        rm -f "/usr/lib/s6-rc/policy/shared/runlevel_$j/contents.d/$i"
      done
    fi
  done
fi

list=$($dbx atomics "$@")
for i in $list ; do
  touch "/usr/lib/s6-rc/masked/$i"
done

# Masking succeeded either way. Until 2026-09-22 the "test -n" below was the
# last command of the script, so masking an already-disabled service exited 1
# and every caller (the Puppet provider above all) reported a failure.
if test -n "$todisable" ; then
  exec /usr/lib/s6-policy-common/bin/svctl-compile
fi

exit 0
