#!/bin/sh -e

if test -z "$1" ; then
  echo "svctl-disable: usage: svctl-disable 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
elif test x"$policy" = x"shared" ; then
  isexclusive=false
else
  echo "svctl-disable: fatal: /usr/lib/s6-rc/policy/current should be a relative symlink to either shared or exclusive" 1>&2
  exit 100
fi

needcompile=false
for i in $($dbx atomics "$@") ; do
  if test -d "/usr/lib/s6-rc/sources/$i" ; then
    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
    needcompile=true
  else
    echo "svctl-disable: warning: service $i not found in /usr/lib/s6-rc/sources"
  fi
done

if $needcompile ; then
  exec /usr/lib/s6-policy-common/bin/svctl-compile
fi
