#!/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" 
todisable=$($dbx contents "$top" | grep -Fx -f "$tmp")

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
    if $isexclusive ; then
      rm -f "/usr/lib/s6-rc/policy/exclusive/top/$i"
    else
      for j in 2 3 4 5 ; do
        rm -f "/usr/lib/s6-rc/policy/shared/runlevel_$j/$i"
      done
    fi
  done
fi

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

if test -n "$todisable" ; then
  exec /usr/lib/s6-policy-common/bin/svctl-compile
fi
